1. 程式人生 > >springboot整合快取redis-cache

springboot整合快取redis-cache

1、pom新增必要的redis、cache、common依賴
 <!--cache 依賴包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

        <!--redis 依賴包-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--redission 依賴包-->
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.5.4</version>
            <exclusions>
                <exclusion>
                    <artifactId>cache-api</artifactId>
                    <groupId>javax.cache</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <!--aspectj 依賴包-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>
2、properties新增redis相關配置

#redis配置
#master的ip地址
spring.redis.host=127.0.0.1
#埠號
spring.redis.port=6379
# Redis伺服器連線密碼(預設為空)
spring.redis.password=
#客戶端超時時間單位是毫秒 預設是2000
spring.redis.timeout=30000
#連線池的最大資料庫連線數。設為0表示無限制,如果是jedis 2.4以後用redis.maxTotal
spring.redis.lettuce.pool.max-active=50
#最小空閒數
spring.redis.lettuce.pool.min-idle=5
#最大建立連線等待時間。如果超過此時間將接到異常。設為-1表示無限制。
spring.redis.lettuce.pool.max-wait=5000ms
# 連線池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.lettuce.shutdown-timeout=100ms
#最大空閒數
spring.redis.lettuce.pool.max-idle=50
#字首
spring.redis.prefix=CarryJey

3、啟動類編寫相關啟動bean
添加註解:@EnableCaching

新增必要的啟動bean

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 使用Jackson2JsonRedisSerialize 替換預設序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        // 設定value的序列化規則和 key的序列化規則
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Configuration
    public static class CacheConfig extends CachingConfigurerSupport {
        @Autowired
        private RedisConfig redisConfig;

        @Bean
        public GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer() {

            GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer();

            try {
                Field mapperField = ReflectionUtils.findField(GenericJackson2JsonRedisSerializer.class, "mapper");
                mapperField.setAccessible(true);

                ObjectMapper objectMapper = (ObjectMapper) mapperField.get(serializer);
                // java8 time
                objectMapper.findAndRegisterModules();
                objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

                mapperField.setAccessible(false);
            } catch (Exception e) {
                logger.warn("Config object mapper of GenericJackson2JsonRedisSerializer error.", e);
                throw new RuntimeException(e);
            }

            return serializer;
        }

        @Bean
        public RedisCacheConfiguration redisCacheConfiguration() {
            return RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofHours(2))
                    .computePrefixWith(cacheName -> redisConfig.prefix + ":" + cacheName + ":")
                    .serializeValuesWith(
                            RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()));
        }
    }

    @Component
    @ConfigurationProperties(prefix = "spring.redis")
    public static class RedisConfig {
        private String prefix = "CarryJey";

        public void setPrefix(String prefix) {
            this.prefix = prefix;
        }

        public String getPrefix() {
            return prefix;
        }

        public String addPrefix(String key) {
            return prefix + ":" + key;
        }
    }

    @Autowired
    private RedisProperties redisProperties;
4、dao層使用相關注解進行快取的使用,資料連結:https://blog.csdn.net/qq_37465368/article/details/81385395