1、 pom 文件
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
2、yml文件
#Redis缓存配置 redis: #监察员模式开关 usingSentinel: false # Redis数据库索引(默认为0) database: 0 # Redis服务器地址 host: 127.0.0.1 # Redis服务器连接端口 port: 6379 # 连接超时时间(毫秒) timeout: 6000 # 连接池最大连接数(使用负值表示没有限制) max-active: 50 # 连接池中的最大空闲连接 max-idle: 50 # 连接池最大阻塞等待时间(使用负值表示没有限制) max-wait: 3000 # 连接池中的最小空闲连接 min-idle: 10
3、spring 的配置文件
package com.july.admin.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; 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.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.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import java.lang.reflect.Method; import java.time.Duration; import java.util.HashMap; import java.util.Map; /** * Redis + @Cachable 配置文件 * @author july */ @CacheConfig @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport{ @Bean @Override 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 RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { return new RedisCacheManager( RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory), // 默认策略,未配置的 key 会使用这个 this.getRedisCacheConfigurationWithTtl( 60), // 指定 key 策略 this.getRedisCacheConfigurationMap() ); } @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; } private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() { Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>(); //SsoCache和BasicDataCache进行过期时间配置 redisCacheConfigurationMap.put("messageCache", this.getRedisCacheConfigurationWithTtl(30 * 60)); //自定义设置缓存时间 redisCacheConfigurationMap.put("userCache", this.getRedisCacheConfigurationWithTtl(60)); return redisCacheConfigurationMap; } private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) { Jackson2JsonRedisSerializer<Object> 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); RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig(); redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith( RedisSerializationContext .SerializationPair .fromSerializer(jackson2JsonRedisSerializer) ).entryTtl(Duration.ofSeconds(seconds)); return redisCacheConfiguration; } }
4、开始使用
/** * @author: july * @date: 2020/1/10 22:21 * @description: */ @Controller public class MenuController { @Autowired private PermissionService permissionService; @GetMapping("menu") @ResponseBody @Cacheable("menu") public Result menu(){ List<PermissionTreeDTO> list = permissionService.getPermissionsInTree(); return Result.success(list); } }