redis简单使用
- 集成依赖
org.springframework.boot
spring-boot-starter-data-redis
- application.yml连接redis
spring:
redis:
host: localhost
port: 6379
database: 0
jedis:
pool:
max-active: 8
max-wait: 1ms
max-idle: 4
min-idle: 0
cache:
redis:
time-to-live: 1800000 #设置缓存数据的过期时间
- 注入RedisTemplate
@Autowired
private RedisTemplate redisTemplate;
- 配置RedisConfig类继承CachingConfigurerSupport防止在存入key的时候在redis中找不到key
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate
- 使用
@PutMapping
public R update(@RequestBody DishDto dishDto){
dishService.updateWithFlavor(dishDto);
//清理redis缓存的菜品数据
// Set keys = redisTemplate.keys("dish_*");
// redisTemplate.delete(keys);
String key="dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
redisTemplate.delete(key);
return R.success("修改成功");
}
注解缓存
- 配置依赖
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.boot
spring-boot-starter-cache
- application.yml连接redis
spring:
redis:
host: localhost
port: 6379
database: 0
jedis:
pool:
max-active: 8
max-wait: 1ms
max-idle: 4
min-idle: 0
cache:
redis:
time-to-live: 1800000 #设置缓存数据的过期时间
- 开启缓存注解功能,在启动类上
@Slf4j
@SpringBootApplication
@ServletComponentScan//扫描过滤器
@EnableTransactionManagement//开启事务支持
@EnableCaching//开启缓存注解功能
public class ReggieApplication {
public static void main(String[] args) {
SpringApplication.run(ReggieApplication.class,args);
log.info("Project start running...");
}
}
- 使用
@PostMapping
@CacheEvict(value = "setmealCache",allEntries = true)
public R save(@RequestBody SetmealDto setmealDto){
log.info(setmealDto.toString());
setmealService.saveWithDish(setmealDto);
return R.success("添加成功");
}
解释:cacheEvict表示在删除时删除缓存中的内容,value:从setmealCache缓存中删除,allEntries=true:删除缓存中所有内容
@Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
public R> list(Setmeal setmeal){
log.info(setmeal.toString());
LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
queryWrapper.eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());
queryWrapper.orderByDesc(Setmeal::getUpdateTime);
List setmealList = setmealService.list(queryWrapper);
return R.success(setmealList);
}
解释:Cacheable表示在运行完程序之后把参数保存在缓存中,value:给缓存起的名字,key:要取值的key,"#setmeal.categoryId+‘_’+#setmeal.status"为设置key的内容用#参数来动态取值。