@Cacheable 注解的 @CacheManager 示例

@Cacheable 注解的使用

开发中经常会使用Redis 缓存,可以使用 @Cacheable 相关的注解来操作缓存。

详情见:https://blog.csdn.net/sinat_32502451/article/details/134310654

CacheManager

@Cacheable 注解有一个属性,cacheManager ,可以自定义缓存管理器。

pom.xml 依赖包:

注意,需要用 springBoot 2.0 以上的 版本。

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

application.properties

配置如下:

# ############## redis config##########

redis.host= xx.xx.xx.xx
redis.port=6579
redis.password=xxxx

redis.master=xx
redis.host.proxy=xxxx
redis.port.proxy=6579
redis.password.proxy=xxxx

#redis cluster
redis.cache.clusterNodes=xxx:xxx,xxx:xxx,xxx:xxx
redis.cache.password=xxx
redis.cache.commandTimeout=1000
redis.cache.soTimeout=3000
redis.cache.maxAttempts=5
redis.cache.expireSeconds=120
redis.pool.maxActive=30
redis.pool.maxIdle=10
redis.pool.maxTotal=1024
redis.pool.maxWaitMillis=2000
redis.pool.testOnBorrow=false


# ############## redis config end##########

代码如下:

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
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.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.*;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;


@Configuration
@EnableCaching
public class RedisConfig {
    @Value("${spring.redis.host:localhost}")
    private String host;
    @Value("${spring.redis.port:6379}")
    private int port;
    @Value("${spring.redis.timeout:30000}")
    private int timeout;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.pool.max-active:8}")
    private int maxActive;
    @Value("${spring.redis.pool.max-wait:-1}")
    private int maxWait;
    @Value("${spring.redis.pool.max-idle:8}")
    private int maxIdle;
    @Value("${spring.redis.pool.min-idle:0}")
    private int minIdle;


    /**
     * 用 @Primary 注解修饰,表示是默认的缓存管理器。
     * <p>
     * 缓存一小时。
     *
     * @return
     */
    @Bean
    @Primary
    public CacheManager cacheManagerOneHour() {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = getJackson2JsonRedisSerializer();
        JedisConnectionFactory jedisConnectionFactory = redisConnectionFactory();
        return RedisCacheManager.builder(jedisConnectionFactory)
                .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig()
                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                        //entryTtl 表示缓存的时间. 24*60
                        .entryTtl(Duration.ofMinutes(1440)))
                .build();
    }


    /**
     * 缓存一天
     *
     * @return
     */
    @Bean
    public CacheManager cacheManagerOneDay() {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = getJackson2JsonRedisSerializer();
        JedisConnectionFactory jedisConnectionFactory = redisConnectionFactory();
        return RedisCacheManager.builder(jedisConnectionFactory)
                .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig()
                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                        //entryTtl 表示缓存的时间
                        .entryTtl(Duration.ofDays(1)))
                .build();
    }


    /**
     * 序列化
     *
     * @return
     */
    public Jackson2JsonRedisSerializer<Object> getJackson2JsonRedisSerializer() {
        Jackson2JsonRedisSerializer<Object> 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);
        return jackson2JsonRedisSerializer;
    }


    /**
     * redis 连接
     *
     * @return
     */
    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(host);
        redisStandaloneConfiguration.setPort(port);
        redisStandaloneConfiguration.setPassword(password);
//        redisStandaloneConfiguration.setDatabase();
        return new JedisConnectionFactory(redisStandaloneConfiguration);
    }

}

posted on   乐之者v  阅读(160)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-08-08 大型网站应用之海量数据和高并发解决方案总结一二 【转载】
2018-08-08 SpringBoot中使用Redis
2016-08-08 python的range函数与切片操作符
2016-08-08 python简单基础代码
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示