springboot 接入redis作为缓存
1.pom
org.springframework.boot
spring-boot-starter-redis
1.4.7.RELEASE
org.springframework.boot
spring-boot-starter-cache
2.1.6.RELEASE
2. 配置
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
/**
* redis有三种模式-standalone,sentinel,cluster,
* @EnableCaching 开启缓存
*/
@Configuration
@EnableCaching
public class SpringRedisSessionConfig{
private String redisHost = "127.0.0.1";
private Integer port = 6379;
@Bean("connectionFactory")
public RedisConnectionFactory redisStandaloneMasterConnectionFactory() {
RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration();
redisConfig.setHostName(redisHost);
redisConfig.setPort(port);
redisConfig.setDatabase(0);
RedisConnectionFactory lettuceConnectionFactory = new JedisConnectionFactory(redisConfig);
return lettuceConnectionFactory;
}
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration= RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(1000)); //entryTtl 代表过期时间
return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
// 对象序列化
@Bean
public RedisTemplate
3.定义key 生成规则
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.lang.reflect.Method;
/**
* 自定义缓存的 key生成
*/
@Component
public class MyKeyGenerator implements KeyGenerator {
@Override
public Object generate(Object o, Method method, Object... objects) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(o.getClass().getSimpleName())
.append("_")
.append(method.getName())
.append("_")
.append(StringUtils.arrayToDelimitedString(objects, "_"));
return stringBuffer.toString();
}
}
4. 使用
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
/**
* @Cacheable 加上代表需要缓存的方法
* @CacheEvict 注解代表需要清除缓存
* cacheNames 为缓存的key
*
* 这样使用缺点是 缓存不会自动过期,只有调用 @CacheEvict 的方法才会过期
*
*/
@RequestMapping
@RestController
public class Demo01Controller {
@GetMapping("a")
@Cacheable(cacheNames = "demo01",keyGenerator = "myKeyGenerator")
public String test1() {
System.out.println(LocalDateTime.now() + " 进入了方法 ");
return "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
}
@GetMapping("b")
public String test2() {
System.out.println(LocalDateTime.now() + " 进入了方法 ");
return "bbbbbbbbbbbbbbbbbb";
}
@CacheEvict(cacheNames = "demo01", allEntries = true)
@GetMapping("clear")
public String clear() {
return "清除成功";
}
}
其中key 可以使用el表达式
|
属性名称 |
描述 |
示例 |
|
methodName |
当前方法名 |
#root.methodName |
|
method |
当前方法 |
#root.method.name |
|
target |
当前被调用的对象 |
#root.target |
|
targetClass |
当前被调用的对象的class |
#root.targetClass |
|
args |
当前方法参数组成的数组 |
#root.args[0] |
|
caches |
当前被调用的方法使用的Cache |
#root.caches[0].name |
例如:
@GetMapping("c")
// @Cacheable(cacheNames = "demo01",key = "#root.method.name")
@Cacheable(cacheNames = "demo01",key = "#user.id.toString().concat(#user.name)") // 支持el表达式,注意不能为空
public String test3(@RequestBody User user) {
System.out.println("user = " + user);
System.out.println(LocalDateTime.now() + " 进入了方法 ");
return "bbbbbbbbbbbbbbbbbb";
}
5. 缓存设置时间
可以在CacheManager 设置过期时间,见上面配置第2点。