首先引入POM依赖
<!-- 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>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.31</version>
</dependency>
加入配置
这里我用的是YML的格式
spring:
redis:
#数据库索引
database: 0
host: 192.168.1.116
port: 6379
password:
jedis:
pool:
#最大连接数
max-active: 8
#最大阻塞等待时间(负数表示没限制)
max-wait: -1
#最大空闲
max-idle: 8
#最小空闲
min-idle: 0
#连接超时时间
timeout: 10000spring:
redis:
#数据库索引
database: 0
host: 192.168.1.116
port: 6379
password:
jedis:
pool:
#最大连接数
max-active: 8
#最大阻塞等待时间(负数表示没限制)
max-wait: -1
#最大空闲
max-idle: 8
#最小空闲
min-idle: 0
#连接超时时间
timeout: 10000
正常情况下这样就可以直接使用了
@Service
public class BuyerServiceImpl implements BuyerService {
@Autowired
private BuyerMapper buyerMapper;
@Autowired
protected RedisTemplate<String, String> redisTemplate;
/**
* 测试查询
* @return
*/
@Override
public List<TestBean> queryBuyerTest() {
//缓存key
String cacheKey = "redisSet";
//查询缓存中是否有该缓存
String cacheValue =redisTemplate.opsForValue().get(cacheKey);
//如果有 怎么办 (则把缓存中的数据取出即可)
if(StringUtils.isNotEmpty(cacheValue)){
System.out.println("走缓存了");
List<TestBean> test=JSON.parseArray(cacheValue,TestBean.class);
return test;
}else{ //如果没有 怎么办 (去数据库查询并缓存到redis中)
System.out.println("没走缓存");
List<TestBean> testBeans = buyerMapper.queryBuyerTest();
String jsonString = JSON.toJSONString(testBeans);
//缓存数据到redis中
redisTemplate.opsForValue().set(cacheKey, jsonString);
//设置权限缓存的过期时间 30分钟
redisTemplate.expire(cacheKey,30,TimeUnit.MINUTES);
return testBeans;
}
}
}
去redis的客户端里面查看缓存如下