SpringBoot2集成RedisCacheManager

  • 這里是SpringBoot2集成RedisCacheManager的方式
    SpringBoot1配置CacheManager有區(qū)別

maven依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.0.3.RELEASE</version>
</dependency>

RedisConfig

@Configuration
@ConfigurationProperties(prefix = "redis")
@EnableCaching  // 需要這個注解才能啟用注解驅(qū)動的緩存管理功能
public class RedisConfig {
    private String clusterNodes;
    private String redisHost;
    private int redisPort;
    private String redisPasswd;
    private int timeOut = 2000;
    private int redirects = 8;

    @Bean // redis配置
    public RedisClusterConfiguration getClusterConfiguration() {
        Map<String, Object> source = Maps.newHashMap();
        source.put("spring.redis.cluster.nodes", clusterNodes);
        source.put("spring.redis.cluster.timeout", timeOut);
        source.put("spring.redis.cluster.max-redirects", redirects);
        return new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source));
    }

    @Bean // redis連接
    public RedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory cf = null;
        if (clusterNodes != null && !clusterNodes.isEmpty()) {
            cf = new JedisConnectionFactory(getClusterConfiguration());
        } else {
            RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
            redisStandaloneConfiguration.setHostName(redisHost);
            redisStandaloneConfiguration.setPort(redisPort);
            redisStandaloneConfiguration.setPassword(RedisPassword.of(redisPasswd));
            cf = new JedisConnectionFactory(redisStandaloneConfiguration);
        }
        cf.afterPropertiesSet();
        return cf;
    }

    @Bean // 實際使用的redisTemplate营曼,可以直接注入到代碼中,直接操作redis
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setConnectionFactory(redisConnectionFactory());
        return redisTemplate;
    }

    @Bean // 關(guān)聯(lián)redis到注解
    CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {

        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);

        // 默認(rèn)配置颜阐,過期時間指定是30分鐘
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
        defaultCacheConfig.entryTtl(Duration.ofMinutes(30));

        // redisExpire1h cache配置跃惫,過期時間指定是1小時宙攻,緩存key的前綴指定成prefixaaa_(存到redis的key會自動添加這個前綴)
        RedisCacheConfiguration userCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().
                entryTtl(Duration.ofHours(1)).prefixKeysWith("prefixaaa_");
        Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
        redisCacheConfigurationMap.put("redisExpire1h", userCacheConfiguration);

        RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, defaultCacheConfig, redisCacheConfigurationMap);
        return cacheManager;
    }

使用注解驅(qū)動的緩存管理功能

  • TestUser必須實現(xiàn) implements Serializable,不然無法序列化到redis;而且serialVersionUID務(wù)必指定髓需,不然增加字段玻褪,會導(dǎo)致反序列化回來失敗
  • key的語法是SpEL
    注解使用在interface接口上肉渴,key需要使用#p0 #p0.id這種index下標(biāo)的方式訪問,0表示第一個入?yún)⒋洌源祟愅疲?br> 其他具體的bean同规,key可以使用#id #testUser.id方式訪問,interface接口用這種方式訪問會報錯:java.lang.IllegalArgumentException: Null key returned for cache operation
  • value對應(yīng)的是cacheManager中的redisCacheConfigurationMap中的配置(map可以放多個配置)窟社,這里指定的是redisExpire1h券勺;
    不寫或者匹配不上,使用的是cacheManager中默認(rèn)的defaultCacheConfig
@Repository("testUserDAO")
public interface TestUserDAO {
    // 查詢操作---緩存
    @Cacheable(value = "redisExpire1h", key = "'test_user_'.concat(#p0)")
    TestUser selectById(@Param("id") String id);

    // 更新操作---清除緩存
    @CacheEvict(value = "redisExpire1h", key = "'test_user_'.concat(#p0.id)")
    Integer updateConfigByCorp(TestUser testUser);
}

null值處理

  • 如上配置的話灿里,null值會被緩存关炼,所以insert的時候也需要CacheEvict;不然先查(緩存了null)匣吊,再插儒拂,后查詢可能一直返回null
    nullValue緩存如下: "\xac\xed\x00\x05sr\x00+org.springframework.cache.support.NullValue\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x00xp"

參考

https://docs.spring.io/spring/docs/3.1.0.M1/spring-framework-reference/html/cache.html#cache-spel-context

為什么阿里巴巴要求程序員謹(jǐn)慎修改serialVersionUID 字段的值

擴展

Mysql緩存機制寸潦,Mybatis緩存機制

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市社痛,隨后出現(xiàn)的幾起案子见转,更是在濱河造成了極大的恐慌,老刑警劉巖褥影,帶你破解...
    沈念sama閱讀 221,273評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件池户,死亡現(xiàn)場離奇詭異,居然都是意外死亡凡怎,警方通過查閱死者的電腦和手機校焦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,349評論 3 398
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來统倒,“玉大人寨典,你說我怎么就攤上這事》看遥” “怎么了耸成?”我有些...
    開封第一講書人閱讀 167,709評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長浴鸿。 經(jīng)常有香客問我井氢,道長,這世上最難降的妖魔是什么岳链? 我笑而不...
    開封第一講書人閱讀 59,520評論 1 296
  • 正文 為了忘掉前任花竞,我火速辦了婚禮,結(jié)果婚禮上掸哑,老公的妹妹穿的比我還像新娘约急。我一直安慰自己,他們只是感情好苗分,可當(dāng)我...
    茶點故事閱讀 68,515評論 6 397
  • 文/花漫 我一把揭開白布厌蔽。 她就那樣靜靜地躺著,像睡著了一般摔癣。 火紅的嫁衣襯著肌膚如雪奴饮。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,158評論 1 308
  • 那天供填,我揣著相機與錄音拐云,去河邊找鬼。 笑死近她,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的膳帕。 我是一名探鬼主播粘捎,決...
    沈念sama閱讀 40,755評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼薇缅,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了攒磨?” 一聲冷哼從身側(cè)響起泳桦,我...
    開封第一講書人閱讀 39,660評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎娩缰,沒想到半個月后灸撰,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,203評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡拼坎,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,287評論 3 340
  • 正文 我和宋清朗相戀三年浮毯,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片泰鸡。...
    茶點故事閱讀 40,427評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡债蓝,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出盛龄,到底是詐尸還是另有隱情饰迹,我是刑警寧澤,帶...
    沈念sama閱讀 36,122評論 5 349
  • 正文 年R本政府宣布余舶,位于F島的核電站啊鸭,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏匿值。R本人自食惡果不足惜赠制,卻給世界環(huán)境...
    茶點故事閱讀 41,801評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望千扔。 院中可真熱鬧憎妙,春花似錦、人聲如沸曲楚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,272評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽龙誊。三九已至抚垃,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間趟大,已是汗流浹背鹤树。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留逊朽,地道東北人罕伯。 一個月前我還...
    沈念sama閱讀 48,808評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像叽讳,于是被迫代替她去往敵國和親追他。 傳聞我的和親對象是個殘疾皇子坟募,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,440評論 2 359