Redis 在Springboot中的使用體現
阿新 • • 發佈:2018-12-18
安裝Redis步驟此處不做介紹,程式碼的執行需要開啟Redis。
一、相關程式碼與配置
目錄結構
1、application.properties
#==== redies ==== # Redis資料庫索引(預設為0) spring.redis.database=0 # Redis伺服器地址 spring.redis.host=127.0.0.1 # 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
2、RedisConfig類
package com.demo.myone.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.CacheManager; 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 com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; /** * Description:Redis快取配置類 * User: adg * Date: 2018/10/18 */ @Configuration @EnableCaching //開啟快取 public class RedisConfig extends CachingConfigurerSupport{ @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.timeout}") private int timeout; //自定義快取key生成策略 @Bean public KeyGenerator wiselyKeyGenerator() { 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(); }; } //快取管理器 @Bean public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) { RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); //設定快取過期時間 cacheManager.setDefaultExpiration(10000); return cacheManager; } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory){ StringRedisTemplate template = new StringRedisTemplate(factory); setSerializer(template);//設定序列化工具 template.afterPropertiesSet(); return template; } private void setSerializer(StringRedisTemplate template){ @SuppressWarnings({ "rawtypes", "unchecked" }) 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); } }
二、相關注解
- @EnableCache開啟快取功能,專案只需要在某個類上加一次該註解即可。
- @CacheConfig有時候一個類中可能會有多個快取操作,而這些快取操作可能是重複的。這個時候可以使用@CacheConfig,它是一個類級別的註解,允許共享快取的名稱、KeyGenerator、CacheManager 和CacheResolver。(這樣配置了,就不用在各個操作中單獨配name=“xxx”)
- @Cacheable將查詢結果快取到redis中,(key="#p0")指定傳入的第一個引數作為redis的key。
- @CachePut,指定key,將更新的結果同步到redis中
- @CacheEvict,指定key,刪除快取資料,allEntries=true,方法呼叫後將立即清除快取
三、遇到的問題
報錯:
Null key returned for cache operation (maybe you are using named params on classes without debug info?)
原因:
快取機制是作用到Service層的,而dao或者repository層快取用註解用key的話它會認定為null。這樣我們就用KeyGenerator來提前生成key的生成策略。
解決:
把以下程式碼加入添加了 (@EnableCaching //開啟快取功能)註解的類中
//自定義快取key生成策略
@Bean
public KeyGenerator wiselyKeyGenerator() {
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();
};
}
這樣就能使用了
@Cacheable(keyGenerator = "wiselyKeyGenerator")
User findById(@Param("id") int id)
四、使用效果
在配置檔案中加入
logging.level.com.demo.myone.dao=debug
即可在控制檯打印出sql。
1、先新增一條資料(這時快取中還沒有該資料)
2、第一次查詢該條資料
此時是從資料庫查出的資料
3、當再次執行時
可以看到,第二次沒有列印sql,此時是從快取中查出了資料。