redis的应用场景
缓存(数据查询、短连接、新闻内容、商品内容等等)。(最多使用) 分布式集群架构中的session分离。 聊天室的在线好友列表。 任务队列。(秒杀、抢购、12306等等) 应用排行榜。 网站访问统计。 数据过期处理(可以精确到毫秒)
1.添加pox.xml依赖
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 通用池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
2.application.yml配置Redis连接数据源
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/*.xml
configuration:
map-underscore-to-camel-case: true
# 日志配置
logging:
level:
com.xxx.xxx: debug
org.springframework: warn
3.编写Redis的配置类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
/**
* 简化RedisTemplate基类的写法
*/
@Component
public class RedisUtils {
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
* 读取缓存
*
* @param key
* @return
*/
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自己去测试一下吧
版权声明:本文为f234344435原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。