欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot集成Redis使用Cache緩存的實(shí)現(xiàn)方法

 更新時(shí)間:2024年10月12日 10:25:21   作者:秋意鐘  
SpringBoot通過配置RedisConfig類和使用Cache注解可以輕松集成Redis實(shí)現(xiàn)緩存,主要包括@EnableCaching開啟緩存,自定義key生成器,改變序列化規(guī)則,以及配置RedisCacheManager,本文為使用SpringBoot與Redis處理緩存提供了詳實(shí)的指導(dǎo)和示例,感興趣的朋友一起看看吧

使用SpringBoot集成Redis使用Cache緩存只要配置相應(yīng)的配置類,然后使用Cache注解就能實(shí)現(xiàn)

RedisConfig配置

新建RedisConfig配置類

package com.bdqn.redis.config;
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.cache.interceptor.KeyGenerator;
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.lang.reflect.Method;
import java.time.Duration;
/**
 * @author cuishujian
 * @date 2024/9/25
 */
@Configuration
@EnableCaching// 開啟緩存
public class RedisConfig extends CachingConfigurerSupport {
    /**
     * 自定義生成 key的規(guī)則
     * 緩存對(duì)象集合中,緩存是以 key-value 形式保存的
     * 當(dāng)不指定緩存的 key時(shí),SpringBoot會(huì)使用 SimpleKeyGenerator 生成 key
     * @return
     */
    @Bean
    public KeyGenerator keyGenerator(){
        return new KeyGenerator(){
            public Object generate(Object target, Method method, Object... params){
                // 格式化緩存key字符串
                StringBuilder sb = new StringBuilder();
                // 追加類名
                sb.append(target.getClass().getName());
                // 追加方法名
                sb.append(method.getName());
                // 遍歷參數(shù)并且追加
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 解決查詢緩存轉(zhuǎn)換異常的問題
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        // 使用Jackson2JsonRedisSerialize 替換默認(rèn)序列化
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(om, Object.class);
        // 設(shè)置value的序列化對(duì)象和key的序列化對(duì)象
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
    /**
     * 采用RedisCacheManager作為緩存管理器
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory){
        // 創(chuàng)建Redis序列化對(duì)象
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        // 解決查詢緩存轉(zhuǎn)換異常的問題
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        // 創(chuàng)建Jackson的序列化對(duì)象
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(om, Object.class);
        // 配置序列化(解決亂碼問題)
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                // 7天緩存過期
                .entryTtl(Duration.ofDays(7))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

以上代碼說明如下:

@EnableCaching:使用此注解開啟緩存

keyGenerator():使用此方法自定義key生成規(guī)則

redisTemplate():使用此方法改變默認(rèn)的序列化規(guī)則,將數(shù)據(jù)序列化為json格式。當(dāng)我們引入了spring-boot-starter-data-reids時(shí),RedisAutoConfiguration自動(dòng)配置類幫我們注入了RedisTemplate<Object,Object>和StringRedisTemplate兩個(gè)組件來操作redis,其中RedisTemplate<Object,Object>的鍵值都是對(duì)象,StringRedisTemplate用來操作字符串的。RedisTemplate使用的是JdkSerializationRedisSerializer,存入數(shù)據(jù)會(huì)將數(shù)據(jù)先序列化成字節(jié)數(shù)據(jù)然后再存入Redis,如果希望將數(shù)據(jù)序列化為json格式,則要改變默認(rèn)的序列化規(guī)則

cacheManager():使用此方法自定義RedisCacheManager改變默認(rèn)的序列化規(guī)則,將數(shù)據(jù)序列化為json格式

Cache注解

@Cacheable

  • 作用:主要針對(duì)方法配置,能夠根據(jù)方法的請(qǐng)求參數(shù)對(duì)其結(jié)果進(jìn)行緩存。在查詢時(shí),會(huì)先從緩存中取數(shù)據(jù),若不存在才再發(fā)起對(duì)數(shù)據(jù)庫的訪問。
  • 參數(shù):
    • value/cacheNames:指定緩存存儲(chǔ)的集合名。
    • key:緩存對(duì)象存儲(chǔ)在Map集合中的key值,非必需,缺省按照函數(shù)的所有參數(shù)組合作為key值,若自己配置需使用SpEL表達(dá)式。
    • condition:緩存對(duì)象的條件,非必需,也需使用SpEL表達(dá)式,只有滿足表達(dá)式條件的內(nèi)容才會(huì)被緩存。
    • unless:另一個(gè)緩存條件參數(shù),非必需,也需使用SpEL表達(dá)式,但判斷時(shí)機(jī)在函數(shù)被調(diào)用之后,所以它可以通過對(duì)result進(jìn)行判斷。
    • keyGenerator:用于指定key生成器,非必需。
    • cacheManager:用于指定使用哪個(gè)緩存管理器,非必需。
    • cacheResolver:用于指定使用哪個(gè)緩存解析器,非必需。
  • 示例:@Cacheable(value = "user", key = "#id"),表示使用id作為key,將方法的返回結(jié)果緩存到名為“user”的緩存中。

@CachePut

  • 作用:主要針對(duì)方法配置,能夠根據(jù)方法的請(qǐng)求參數(shù)對(duì)其結(jié)果進(jìn)行緩存,并且每次都會(huì)觸發(fā)真實(shí)方法的調(diào)用(與@Cacheable不同)。主要用于數(shù)據(jù)新增和修改操作上。
  • 參數(shù):與@Cacheable類似。
  • 示例:@CachePut(value = "user", key = "#user.id"),表示以u(píng)ser.id作為key,將方法的返回結(jié)果更新到名為“user”的緩存中。

@CacheEvict

  • 作用:主要針對(duì)方法配置,能夠根據(jù)一定的條件對(duì)緩存進(jìn)行清空。通常用在刪除方法上。
  • 參數(shù):
    • value/cacheNames:指定緩存存儲(chǔ)的集合名。
    • key:指定清除數(shù)據(jù)的key值。
    • allEntries:非必需,默認(rèn)為false。若設(shè)置為true,則清除緩存組件下的所有數(shù)據(jù)。
    • beforeInvocation:非必需,默認(rèn)為false。若設(shè)置為true,則在方法執(zhí)行前清除緩存,否則在方法執(zhí)行后清除。
  • 示例:@CacheEvict(value = "user", key = "#id"),表示從名為“user”的緩存中移除key為id的數(shù)

到此這篇關(guān)于SpringBoot集成Redis使用Cache緩存的文章就介紹到這了,更多相關(guān)SpringBoot使用Cache緩存內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論