SpringBoot 2.3.3 整合redis缓存自定义JSON序列化中遇到的问题。

这两天在学习springboot的缓存机制,发现springboot1.X版本和2.X版本的改动有点大,记录一下

Springboot1.X: 查看源码发现 RedisCacheManager的构造参数中可以使用RedisTemplate<Object, Object> 作为入参的形式来初始化RedisCacheManager. 具体构造参数:

public class RedisCacheManager{
        public RedisCacheManager(RedisOperations redisOperations) {
	   	this(redisOperations, Collections.<String> emptyList());
	}
	public RedisCacheManager(RedisOperations redisOperations, Collection<String> cacheNames) {
		this(redisOperations, cacheNames, false);
	}
	public RedisCacheManager(RedisOperations redisOperations, Collection<String> cacheNames, boolean cacheNullValues) {
 
		this.redisOperations = redisOperations;
		this.cacheNullValues = cacheNullValues;
		setCacheNames(cacheNames);
	}
}

Spring2.X: Spring2.x版本的RedisCacheManager已经取消了使用RedisOperations作为你cacheManager的入参。相对的2.x版本采用了使用RedisCacheWriter和RedisCacheConfiguration作为入参来构造RedisCacheManager对象

public class RedisCacheManager extends AbstractTransactionSupportingCacheManager{
	private RedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration,
			boolean allowInFlightCacheCreation) {
 
		Assert.notNull(cacheWriter, "CacheWriter must not be null!");
		Assert.notNull(defaultCacheConfiguration, "DefaultCacheConfiguration must not be null!");
 
		this.cacheWriter = cacheWriter;
		this.defaultCacheConfig = defaultCacheConfiguration;
		this.initialCacheConfiguration = new LinkedHashMap<>();
		this.allowInFlightCacheCreation = allowInFlightCacheCreation;
	}
    public RedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
		this(cacheWriter, defaultCacheConfiguration, true);
	}
	public RedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration,
			String... initialCacheNames) {
 
		this(cacheWriter, defaultCacheConfiguration, true, initialCacheNames);
	}
 
    public RedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration,
			boolean allowInFlightCacheCreation, String... initialCacheNames) {
 
		this(cacheWriter, defaultCacheConfiguration, allowInFlightCacheCreation);
 
		for (String cacheName : initialCacheNames) {
			this.initialCacheConfiguration.put(cacheName, defaultCacheConfiguration);
		}
	}
    public RedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration,
			Map<String, RedisCacheConfiguration> initialCacheConfigurations) {
 
		this(cacheWriter, defaultCacheConfiguration, initialCacheConfigurations, true);
	}
    public RedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration,
			Map<String, RedisCacheConfiguration> initialCacheConfigurations, boolean allowInFlightCacheCreation) {
 
		this(cacheWriter, defaultCacheConfiguration, allowInFlightCacheCreation);
 
		Assert.notNull(initialCacheConfigurations, "InitialCacheConfigurations must not be null!");
 
		this.initialCacheConfiguration.putAll(initialCacheConfigurations);
	}
}

因此在使用自定义的RedisCacheManager的时候需要做一些改变。 记录一下!该类可以直接使用

package com.atguigu.cache.config;

import com.atguigu.cache.bean.Employee;

import org.springframework.cache.CacheManager;
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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.net.UnknownHostException;
import java.time.Duration;

@Configuration
public class MyRedisConfig {

    @Bean
    public RedisTemplate<Object, Employee> EmpRedisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Employee> serializer = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
        template.setDefaultSerializer(serializer);
        return template;
    }

    //CacheManagerCustomizers可以来定制缓存的一些规则
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory){
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofDays(1))
                .disableCachingNullValues()
                .serializeKeysWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();}
}


Spring 2.3.3 版本可以使用Spring Data Redis整合Redis。 首先,确保你的项目已经导入了Spring Data Redis的依赖。你可以通过Maven或Gradle等构建工具来管理依赖。 接下来,需要配置Redis的连接信息。在Spring的配置文件,添加以下内容: ``` <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="100" /> <property name="maxIdle" value="20" /> <property name="maxWaitMillis" value="3000" /> </bean> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="localhost" /> <property name="port" value="6379" /> <property name="poolConfig" ref="jedisPoolConfig" /> </bean> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory" /> </bean> ``` 上述配置,`hostName`和`port`分别指定了Redis的服务器地址和端口。`jedisPoolConfig`用于配置连接池的参数,例如最大连接数、最大空闲连接数和最大等待时间。`jedisConnectionFactory`是连接工厂,负责创建Redis连接池。`redisTemplate`是Redis操作的核心类,用于执行各种操作,例如存储、获取和删除数据。 配置完成后,可以通过`@Autowired`注解将`redisTemplate`注入到需要使用Redis的类,然后就可以使用Redis相关的操作方法了。例如: ``` @Autowired private RedisTemplate<String, String> redisTemplate; public void saveData() { redisTemplate.opsForValue().set("key", "value"); } public String getData() { return redisTemplate.opsForValue().get("key"); } ``` 以上示例的`opsForValue()`方法用于获取一个用于操作字符串的对象,然后可以使用该对象执行相应的操作。 以上就是通过Spring 2.3.3版本整合Redis的简要步骤。当然,还可以根据具体的需求进行更灵活的配置和使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值