Spring Boot 結合 Redis實現快取
阿新 • • 發佈:2018-11-28
當Redis作為快取使用時,我們可以將它作為Spring Cache的實現,直接通過註解使用@CacheConfig
,@Cacheable
,@CachePut
,@CacheEvict
。
引入依賴(SpringBoot從1.4版本開始,spring-boot-starter-redis
依賴改名了。)
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> </parent> <dependencies> <!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> </dependencies>
配置檔案
#redis # Redis資料庫索引(預設為0) spring.redis.database=0 # Redis伺服器地址 spring.redis.host=localhost # Redis伺服器連線埠 spring.redis.port=6379 # Redis伺服器連線密碼(預設為空) spring.redis.password= # 連線池最大連線數(使用負值表示沒有限制) spring.redis.pool.max-active=100 # 連線池最大阻塞等待時間(使用負值表示沒有限制) spring.redis.pool.max-wait=-1 # 連線池中的最大空閒連線 spring.redis.pool.max-idle=20 # 連線池中的最小空閒連線 spring.redis.pool.min-idle=10 # 連線超時時間(毫秒) spring.redis.timeout=1000 spring.cache.type=redis spring.session.store-type=redis
當不指定快取的key時,SpringBoot會使用SimpleKeyGenerator
生成key。
解決辦法:在@Cacheable
註解引數中指定key,或者自己實現一個KeyGenerator
,在註解中指定KeyGenerator。
或者,繼承CachingConfigurerSupport
並重寫keyGenerator()。解決辦法如下。
配置redis
/** * redis * @author 向振華 * @date 2018/11/26 14:35 */ @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Bean @Override public KeyGenerator keyGenerator() { return (target, method, params) -> { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); }; } /** * 設定快取過期時間 * @param redisTemplate * @return */ @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager rcm = new RedisCacheManager(redisTemplate); rcm.setDefaultExpiration(86400L); 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; } }