SpringBoot实现Redis缓存

通过SpringBoot的注解实现Redis,减少项目依赖以及减少代码量更美观 

使用方式:

@Cacheable(value = "TestServiceImpl", key = "methodName+#id", cacheManager = "cacheManager5m",unless="#result == null")

Redis配置类:

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
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.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
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.StringRedisSerializer;
import org.springframework.util.StringUtils;

import java.time.Duration;

/**
 * redis配置
 * @date 2023/5/9 9:38
 * @author luohao
 */
@Configuration
public class RedisConfig {
    @Value("${spring.application.name}")
    private String appName;

    @Bean(name = "redisTemplate")
    @ConditionalOnClass(RedisOperations.class)
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory, Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    @Bean(name = "cacheManager5m")
    @Primary
    public CacheManager cacheManager5m(RedisConnectionFactory redisConnectionFactory,
                                       Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer) {
        return cacheManager(redisConnectionFactory, jackson2JsonRedisSerializer, Duration.ofMinutes(5), appName);
    }

    @Bean(name = "cacheManager15m")
    public CacheManager cacheManager15m(RedisConnectionFactory redisConnectionFactory,
                                        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer) {
        return cacheManager(redisConnectionFactory, jackson2JsonRedisSerializer, Duration.ofMinutes(15), appName);
    }

    @Bean(name = "cacheManager1h")
    public CacheManager cacheManager1h(RedisConnectionFactory redisConnectionFactory,
                                       Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer) {
        return cacheManager(redisConnectionFactory, jackson2JsonRedisSerializer, Duration.ofHours(1), appName);
    }

    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory,
                                     Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer,
                                     Duration ttl, String appName) {
        final String prefix = StringUtils.isEmpty(appName) ? "" : appName.concat(":");
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                // 设置缓存有效期
                .entryTtl(ttl)
                .disableCachingNullValues()
                .computePrefixWith(cacheName -> prefix.concat(cacheName).concat(":"))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer));
        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(cacheConfiguration)
                .build();
    }

    @Bean
    public Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer() {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(mapper);
        return jackson2JsonRedisSerializer;
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值