您的位置:首页 > 数据库 > Redis

SpringBoot使用Redis做缓存,@Cacheable、@CachePut、@CacheEvict等注解的使用

2018-03-07 11:04 1176 查看

SpringBoot使用Redis做缓存,@Cacheable、@CachePut、@CacheEvict等注解的使用

导入依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>


配置文件

# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.142.142
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0


配置Redis的class文件

package com.frog.mvcdemo.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.lang.reflect.Method;

@CacheConfig
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{

@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
//为给定的方法及其参数生成一个键
//格式为:com.frog.mvcdemo.controller.FrogTestController-show-[params]
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuffer sb = new StringBuffer();
sb.append(target.getClass().getName());//类名
sb.append("-");
sb.append(method.getName());//方法名
sb.append("-");
for (Object param: params ) {
sb.append(param.toString());//参数
}
return sb.toString();
}
};
}

@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//设置默认的过期时间(以秒为单位)
rcm.setDefaultExpiration(600);
//rcm.setExpires();设置缓存区域(按key)的过期时间(以秒为单位)
return rcm;
}

@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}


缓存注解的使用

@Cacheable

Spring 在执行 @Cacheable 标注的方法前先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,执行该方法并将方法返回值放进缓存。

参数: value缓存名、 key缓存键值、 condition满足缓存条件、unless否决缓存条件

@CachePut

和 @Cacheable 类似,但会把方法的返回值放入缓存中, 主要用于数据新增和修改方法

@CacheEvict

方法执行成功后会从缓存中移除相应数据。

参数: value缓存名、 key缓存键值、 condition满足缓存条件、 unless否决缓存条件、 allEntries是否移除所有数据(设置为true时会移除所有缓存)

参考链接:

http://rensanning.iteye.com/blog/2362184

http://blog.csdn.net/whatlookingfor/article/details/51833378

注解使用

package com.frog.mvcdemo.controller;

import com.frog.mvcdemo.entity.Frog;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@CacheConfig(cacheNames = "frogtest")
@RestController
@RequestMapping(value = "/frogtest")
public class FrogTestController {

@Cacheable()
@ApiOperation(value = "获取Frog的列表")
@RequestMapping(value = "",method = RequestMethod.GET)
public List<Frog> show(){
List<Frog> list = new ArrayList<>();
list.add(new Frog(1,"one",2,new Date(),"controllertest"));
list.add(new Frog(2,"two",3,new Date(),"controllertest"));
return list;
}

@Cacheable()
@ApiOperation(value = "获取Frog详细信息",notes = "根据id查询对应Frog信息")
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "int", paramType = "path")
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public Map<String,Object> showById(@PathVariable int id){
Map<String,Object> map = new HashMap<>();
if(id == 1){
map.put("FROG",new Frog(1,"one",3,new Date(),"showById"));
map.put("RESULT","SUCCESS");
}else{
map.put("FROG",null);
map.put("RESULT","ERROR");
}
return map;
}

@CacheEvict(allEntries = true)
@ApiOperation(value = "添加Frog详细信息",notes = "添加一条Frog的
bea5
详细信息")
@ApiImplicitParam(name = "frog", value = "Frog实体", required = true, dataType = "Frog")
@RequestMapping(value = "",method = RequestMethod.POST)
public Map<String,Object> add(@RequestBody Frog frog){
Map<String,Object> map = new HashMap<>();
map.put("FROG",frog);
map.put("RESULT","SUCCESS");
return map;
}

@CacheEvict(allEntries = true)
@ApiOperation(value = "删除Frog详细信息",notes = "根据id删除对应Frog的详细信息")
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "int", paramType = "path")
@RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
public Map<String,Object> deleteById(@PathVariable int id){
Map<String,Object> map = new HashMap<>();
if(id != 0){
map.put("FROG",new Frog(id,"testfrog",id,new Date(),"deleteById"));
map.put("RESULT","SUCCESS");
}else{
map.put("FROG",null);
map.put("RESULT","ERROR");
}
return map;
}

@CacheEvict(allEntries = true)
@ApiOperation(value = "更新Frog详细信息",notes = "根据id更新Frog的详细信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "int",paramType = "path"),
@ApiImplicitParam(name = "frog", value = "Frog实体", required = true, dataType = "Frog")
})
@RequestMapping(value = "/{id}",method = RequestMethod.PUT)
public Map<String,Object> updateById(@PathVariable int id,@RequestBody Frog frog){
Map<String,Object> map = new HashMap<>();
map.put("FROG",frog);
map.put("RESULT","SUCCESS");
map.put("ID",id);
return map;
}
}


缓存一般加在dao层或service层,发生回滚时保持redis中数据不被清空,这里测试在Controller层加缓存。

@CacheConfig(cacheNames = “frogtest”)代表这个Controller下需要缓存的方法对应redis中的缓存名为frogtest~keys。

查询方法都用@Cacheable注解加入缓存

添加更新删除@CacheEvict(allEntries = true)注解表示执行方法时删除redis中缓存名frogtest~keys下所有缓存

redis中keys

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息