Spring Boot集成redis,key自定義生成方式
@Configuration:表示當(dāng)前類屬于一個配置類,類似于一個spring.cfg.xml。
@EnableCaching:表示支持啟用緩存。
自定義配置源碼: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.cache.RedisCachePrefix;import org.springframework.data.redis.core.RedisTemplate; import com.alibaba.fastjson.JSON; /** * redis配置工具類 * @Configuration表示當(dāng)前類屬于配置類 * @EnableCaching表示支持緩存 * @author ouyangjun */@Configuration@EnableCachingpublic class RedisConfig extends CachingConfigurerSupport { /** * redis key生成策略 * target: 類 * method: 方法 * params: 參數(shù) * @return KeyGenerator * 注意: 該方法只是聲明了key的生成策略,還未被使用,需在@Cacheable注解中指定keyGenerator * 如: @Cacheable(value = 'key', keyGenerator = 'cacheKeyGenerator') */ @Bean public KeyGenerator cacheKeyGenerator() {return (target, method, params) -> { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) {// 由于參數(shù)可能不同, hashCode肯定不一樣, 緩存的key也需要不一樣sb.append(JSON.toJSONString(obj).hashCode()); } return sb.toString();}; } /** * redis全局默認(rèn)配置 * @param redisTemplate * @return */ @Bean public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);redisCacheManager.setUsePrefix(true);// key緩存的前綴,以conf開頭RedisCachePrefix cachePrefix = new RedisPrefix('conf');redisCacheManager.setCachePrefix(cachePrefix);// key緩存的過期時間, 600秒redisCacheManager.setDefaultExpiration(600L);return redisCacheManager; }}二)SpringBoot自帶緩存方式
注解說明:
@Cacheable含義:當(dāng)調(diào)用該注解聲明的方法時,會先從緩存中查找,判斷是否有key相同緩存的數(shù)據(jù),如果有,就直接返回數(shù)據(jù),如果沒有,執(zhí)行方法,然后把返回的數(shù)據(jù)以鍵值的方式存儲到緩存中,方便下次同樣參數(shù)請求時,直接從緩存中返回數(shù)據(jù)。
@Cacheable支持如下幾個參數(shù):cacheNames:緩存位置的一段名稱,不能為空,和value一個含義。
value:緩存位置的一段名稱,不能為空,和cacheNames一個含義。
key:緩存的key,默認(rèn)為空,表示使用方法的參數(shù)類型及參數(shù)值作為key,支持SpEL。
keyGenerator:指定key的生成策略。
condition:觸發(fā)條件,滿足條件就加入緩存,默認(rèn)為空,表示全部都加入緩存,支持SpEL。
@CacheEvict含義:當(dāng)存在相同key的緩存時,把緩存清空,相當(dāng)于刪除。
@CacheEvict支持如下幾個參數(shù):cacheNames:緩存位置的一段名稱,不能為空,和value一個含義。
value:緩存位置的一段名稱,不能為空,和cacheNames一個含義。
key:緩存的key,默認(rèn)為空,表示使用方法的參數(shù)類型及參數(shù)值作為key,支持SpEL。
condition:觸發(fā)條件,滿足條件就加入緩存,默認(rèn)為空,表示全部都加入緩存,支持SpEL。
allEntries:true表示清除value中的全部緩存,默認(rèn)為false。
測試代碼:
package hk.com.cre.process.basic.service.impl; import org.springframework.cache.annotation.CacheEvict;import org.springframework.cache.annotation.Cacheable; public class RdisCacheTest { /** * 緩存測試 * 緩存生成規(guī)則: conf:redis:類名方法名參數(shù)hashcode * 注意: @Cacheable注解生成的類型在redis中默認(rèn)都是string * 在每次請求的時候,都是先根據(jù)key到redis查詢是否存在,如不存在則執(zhí)行方法中的代碼 */ @Cacheable(cacheNames = 'redis', keyGenerator = 'cacheKeyGenerator') public String getRedisString(String param1, String param2) {return param1+':'+param2; } /** * 清除緩存 */ @CacheEvict(cacheNames = 'redis', allEntries = true) public String cleanCache() {return 'success'; }}Spring Cache ? KeyGenerator自定義rediskey1. 概述
在此教程中,我們將演示如何使用 Spring Cache 創(chuàng)建自定義密鑰生成器。
2. KeyGenerator這負(fù)責(zé)為緩存中的每個數(shù)據(jù)項生成每個鍵,這些鍵將用于在檢索時查找數(shù)據(jù)項。
此處的默認(rèn)實現(xiàn)是SimpleKeyGenerator ?它使用提供的方法參數(shù)來生成密鑰。這意味著,如果我們有兩個使用相同的緩存名稱和參數(shù)類型集的方法,則很有可能會導(dǎo)致沖突。
它還意味著緩存數(shù)據(jù)可以由另一種方法覆蓋。
3. 自定義密鑰生成器密鑰生成器只需要實現(xiàn)一個方法:
Object generate(Object object, Method method, Object... params)
如果未正確實現(xiàn)或使用,則可能導(dǎo)致覆蓋緩存數(shù)據(jù)。
讓我們來看看實現(xiàn):
public class CustomKeyGenerator implements KeyGenerator { public Object generate(Object target, Method method, Object... params) {return target.getClass().getSimpleName() + '_' + method.getName() + '_' + StringUtils.arrayToDelimitedString(params, '_'); }}
之后,我們有兩種可能的方式使用它;第一種是在應(yīng)用程序Config中聲明一個豆。
請務(wù)必指出,類必須從緩存配置支持或?qū)崿F(xiàn)緩存配置程序擴展:
@EnableCaching@Configurationpublic class ApplicationConfig extends CachingConfigurerSupport { @Bean public CacheManager cacheManager() {SimpleCacheManager cacheManager = new SimpleCacheManager();Cache booksCache = new ConcurrentMapCache('books');cacheManager.setCaches(Arrays.asList(booksCache));return cacheManager; } @Bean('customKeyGenerator') public KeyGenerator keyGenerator() {return new CustomKeyGenerator(); }}
第二種方法是將其用于特定方法:
@Componentpublic class BookService { @Cacheable(value = 'books', keyGenerator = 'customKeyGenerator') public List<Book> getBooks() {List<Book> books = new ArrayList<>();books.add(new Book('The Counterfeiters', 'André Gide'));books.add(new Book('Peer Gynt and Hedda Gabler', 'Henrik Ibsen'));return books; }}4. 結(jié)論
在本文中,我們探討了實現(xiàn)自定義春季緩存的密鑰生成器的方法。
與往常一樣,示例的完整源代碼可在 GitHub 上找到。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
