springboot與redis整合中@Cacheable怎么使用

這篇文章主要講解了“springboot與redis整合中@Cacheable怎么使用”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“springboot與redis整合中@Cacheable怎么使用”吧!

10年積累的成都網(wǎng)站設(shè)計(jì)、做網(wǎng)站經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問(wèn)題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先網(wǎng)站制作后付款的網(wǎng)站建設(shè)流程,更有撫寧免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。

首先我們需要配置一個(gè)緩存管理器,然后才能使用緩存注解來(lái)管理緩存

package com.cherish.servicebase.handler;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //解決查詢緩存轉(zhuǎn)換異常的問(wèn)題
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置序列化(解決亂碼的問(wèn)題),過(guò)期時(shí)間600秒
        RedisCacheConfiguration config = RedisCacheConfiguration
                .defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();

        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
             // 可以給每個(gè)cacheName不同的RedisCacheConfiguration  設(shè)置不同的過(guò)期時(shí)間
            //.withCacheConfiguration("Users",config.entryTtl(Duration.ofSeconds(100)))
                .transactionAware()
                .build();
        return cacheManager;
    }
}

1、@Cacheable

標(biāo)記在方法或者類上,標(biāo)識(shí)該方法或類支持緩存。Spring調(diào)用注解標(biāo)識(shí)方法后會(huì)將返回值緩存到redis,以保證下次同條件調(diào)用該方法時(shí)直接從緩存中獲取返回值。這樣就不需要再重新執(zhí)行該方法的業(yè)務(wù)處理過(guò)程,提高效率。

@Cacheable常用的三個(gè)參數(shù)如下:

cacheNames 緩存名稱
key 緩存的key,需要注意key的寫(xiě)法哈
condition 緩存執(zhí)行的條件,返回true時(shí)候執(zhí)行

示例

    //查詢所有用戶,緩存到redis中
    @GetMapping("/selectFromRedis")
    @Cacheable(cacheNames = "Users",key = "'user'")
    public ResultData getUserRedis(){
        List<User> list = userService.list(null);
        return ResultData.ok().data("User",list);
    }

springboot與redis整合中@Cacheable怎么使用

第一次查詢是從數(shù)據(jù)庫(kù)查詢的,然后緩存到redis中 使用redis可視化工具查看緩存的信息

springboot與redis整合中@Cacheable怎么使用

第二查詢走了緩存控制臺(tái)沒(méi)有輸出 ,所以走的redis緩存 就是在redis中獲取結(jié)果直接返回。

springboot與redis整合中@Cacheable怎么使用

@CacheEvict

標(biāo)記在方法上,方法執(zhí)行完畢之后根據(jù)條件或key刪除對(duì)應(yīng)的緩存。常用的屬性:

  • allEntries boolean類型,表示是否需要清除緩存中的所有元素

  • key 需要?jiǎng)h除的緩存的key

 //調(diào)用這個(gè)接口結(jié)束后,刪除指定的Redis緩存
    @PostMapping("updateUser")
    @CacheEvict(cacheNames ="Users",key = "'user'")
    public ResultData updateUser(@RequestBody User user){
        String id = user.getId();
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("id",id);
        boolean b = userService.update(user, wrapper);
        return ResultData.ok().data("flag",b);
    }
 //不刪除redis緩存
    @PostMapping("updateUser2")
    public ResultData updateUser2(@RequestBody User user){
        String id = user.getId();
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("id",id);
        boolean b = userService.update(user, wrapper);
        return ResultData.ok().data("flag",b);
    }

當(dāng)我們更新數(shù)據(jù)庫(kù)的數(shù)據(jù)時(shí)候,需要把redis的緩存清空。否則我們查詢的數(shù)據(jù)是redis緩存中的數(shù)據(jù),這樣就會(huì)導(dǎo)致數(shù)據(jù)庫(kù)和緩存數(shù)據(jù)不一致的問(wèn)題。

示例  調(diào)用沒(méi)有加 @CacheEvict 注解的接口修改數(shù)據(jù),在查詢得到的數(shù)據(jù)是未修改之前的。

springboot與redis整合中@Cacheable怎么使用

所以在我們調(diào)用修改數(shù)據(jù)的接口的時(shí)候需要清除緩存

加上 @CacheEvict  注解 清除對(duì)應(yīng)的緩存此時(shí)在查詢數(shù)據(jù)發(fā)現(xiàn)數(shù)據(jù)是最新的,跟數(shù)據(jù)庫(kù)保持一致。

springboot與redis整合中@Cacheable怎么使用

過(guò)期時(shí)間

我們已經(jīng)實(shí)現(xiàn)了Spring Cache的基本功能,整合了Redis作為RedisCacheManger,但眾所周知,我們?cè)谑褂?code>@Cacheable注解的時(shí)候是無(wú)法給緩存這是過(guò)期時(shí)間的。但有時(shí)候在一些場(chǎng)景中我們的確需要給緩存一個(gè)過(guò)期時(shí)間!這是默認(rèn)的過(guò)期時(shí)間

springboot與redis整合中@Cacheable怎么使用

數(shù)據(jù)有效期時(shí)間

springboot與redis整合中@Cacheable怎么使用

自定義過(guò)期時(shí)間

springboot與redis整合中@Cacheable怎么使用

使用新的redis配置,再次查詢緩存到數(shù)據(jù)看數(shù)據(jù)有效期

springboot與redis整合中@Cacheable怎么使用

感謝各位的閱讀,以上就是“springboot與redis整合中@Cacheable怎么使用”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)springboot與redis整合中@Cacheable怎么使用這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

當(dāng)前名稱:springboot與redis整合中@Cacheable怎么使用
URL地址:http://muchs.cn/article34/piccse.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、品牌網(wǎng)站制作、外貿(mào)網(wǎng)站建設(shè)、定制開(kāi)發(fā)、品牌網(wǎng)站設(shè)計(jì)品牌網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)