SpringCloud框架如何集成Redis缓存技术
1.首先要在spring boot项目pom.xml文件中添加Redis需要的依赖包,可在生成springboot项目选择自动引入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.在application-dev.yml(spring cloud)/application.properties(spring boot)配置文件中加入Redis的配置信息:
#此为spring cloud配置文件格式
spring:
redis:
database: 0
host: 127.0.0.1
port: 6379
password:
timeout: 500
#此为spring boot格式配置文件
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=20
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=500
3.通过@Autowired注解注入Redis
//注入Redis
@Autowired
private RedisTemplate redisTemplate;
4.我写了一个查询的方法,使用redis缓存技术查询时缓存。
需要注意,你的实体Bean需要序列化!否则500
@PostMapping("queryOrderFeign")
@ResponseBody
public List<OrderBean> queryOrderFeign() {
String redisKay = "queryCom" + 1;
Boolean hasKey = redisTemplate.hasKey(redisKay);
if (hasKey) {
System.out.println("走缓存----");
List<OrderBean> range = redisTemplate.opsForList().range(redisKay, 0, -1);
return range;
} else {
System.out.println("走数据库----");
List<OrderBean> list = userService.queryOrderFeign();
for (int i = 0; i < list.size(); i++) {
redisTemplate.opsForList().leftPush(redisKay, list.get(i));
}
redisTemplate.expire(redisKay, 20, TimeUnit.MINUTES);
return list;
}
}
第一次查询无缓存所以走数据库,第二次查询有缓存,所以直接从缓存里取。完成。