当前位置: 代码迷 >> 综合 >> redis结合springboot
  详细解决方案

redis结合springboot

热度:52   发布时间:2023-10-27 09:27:59.0

 @Autowired
    private RedisTemplate redisTemplate;
public Article findById(String id){
//从缓存中查询当前对象
Article article = (Article)redisTemplate.opsForValue().get("article_"+id);
//如果没有取到
if(article==null){
//从数据库中查询
article = articleDao.findById(id).get();
//存入到缓存中
redisTemplate.opsForValue().set("article_"+id,article);
//redisTemplate.opsForValue().set("article_"+id,article,10,TimeUnit.SECONDS);//设置缓存十秒钟过期
}
return article;
}


//删除redis缓存
redisTemplate.delete("article_"+id);
articleDao.deleteById(id);

springcache:

在启动类上加@EnableCaching

@Cacheable(value=“gathering”,key="#id")//gathering不能取消是标识,这个是增加
public Gathering findById(String id){
article = gatheringDao.findById(id).get();
}

@CacheEvict修改


1.StringRedisTemplate.opsForValue().* //操作String字符串类型
  StringRedisTemplate.opsForValue().

2 StringRedisTemplate.delete(key/collection) //根据key/keys删除
3 StringRedisTemplate.opsForList().*  //操作List类型
4 StringRedisTemplate.opsForHash().*  //操作Hash类型
5 StringRedisTemplate.opsForSet().*  //操作set类型
6 StringRedisTemplate.opsForZSet().*  //操作有序set

stringRedisTemplate.opsForValue().set("test", "100",60*10,TimeUnit.SECONDS);//向redis里存入数据和设置缓存时间  
stringRedisTemplate.opsForValue().get("test")//根据key获取缓存中的val
stringRedisTemplate.boundValueOps("test").increment(-1);//val做-1操作,存的必须是数字
stringRedisTemplate.boundValueOps("test").increment(1);//val +1
stringRedisTemplate.getExpire("test")//根据key获取过期时间
stringRedisTemplate.getExpire("test",TimeUnit.SECONDS)//根据key获取过期时间并换算成指定单位 
stringRedisTemplate.delete("test");//根据key删除缓存
stringRedisTemplate.hasKey("546545");//检查key是否存在,返回boolean值 
stringRedisTemplate.expire("red_123",1000 , TimeUnit.MILLISECONDS);//设置过期时间
stringRedisTemplate.opsForSet().add("red_123", "1","2","3");//向指定key中存放set集合
stringRedisTemplate.opsForSet().isMember("red_123", "1")//根据key查看集合中是否存在指定数据
stringRedisTemplate.opsForSet().members("red_123");//根据key获取set集合