redis的应用场景
缓存(数据查询、短连接、新闻内容、商品内容等等)。(最多使用) 分布式集群架构中的session分离。 聊天室的在线好友列表。 任务队列。(秒杀、抢购、12306等等) 应用排行榜。 网站访问统计。 数据过期处理(可以精确到毫秒)
1.添加pox.xml依赖2.application.yml配置Redis连接数据源org.springframework.boot spring-boot-starter-data-redisorg.apache.commons commons-pool2
server:
port: 8989
spring:
datasource:
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
#连接本地数据库
url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
redis:
host: 127.0.0.1
timeout: 1000
jedis:
pool:
min-idle: 5
max-idle: 10
max-wait: -1
mybatis-plus:
# mapper.xml 文件扫描
mapper-locations: classpath*:/mapper
@Component
public class RedisUtils {
@Autowired
private RedisTemplate redisTemplate;
public String get(final String key) {
return redisTemplate.opsForValue().get(key);
}
public boolean set(final String key, String value) {
boolean result = false;
try {
redisTemplate.opsForValue().set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public boolean getAndSet(final String key, String value) {
boolean result = false;
try {
redisTemplate.opsForValue().getAndSet(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public boolean delete(final String key) {
boolean result = false;
try {
redisTemplate.delete(key);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
4.创建RedisController层:
@RestController
@RequestMapping("/redis")
public class RedisCsController {
//基于基类编写的工具类
@Autowired
private RedisUtils redisUtils;
//查询key
@GetMapping("get/{key}")
public Object get(@PathVariable("key")String key){
return redisUtils.get(key);
}
//插入数据key,value
@PostMapping("save/{key}/{value}")
public String save(@PathVariable("key")String key,@PathVariable("value")String value){
redisUtils.set(key,value);
return "插入成功";
}
//更新key,value
@PostMapping("/update/{key}/{value}")
public String update(@PathVariable("key")String key,@PathVariable("value")String value){
redisUtils.getAndSet(key,value);
return "更新成功";
}
//根据key删除数据
@DeleteMapping("dele/{key}")
public String dele(@PathVariable("key")String key) {
redisUtils.delete(key);
return "删除成功";
}
}
5.最后小伙伴们就自己通过Postman自己去测试一下吧


