package com.jianmu.config;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.support.spring.data.redis.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @author lime
* redis 缓存配置
*/
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConf {
@Bean()
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
GenericFastJsonRedisSerializer fastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
template.setDefaultSerializer(fastJsonRedisSerializer);
//解决fastjson2 redis key 序列话多双引号问题
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
FastRedisSerializer fastRedisSerializer = new FastRedisSerializer();
template.setHashValueSerializer(fastRedisSerializer);
return template;
}
}
class FastRedisSerializer extends GenericFastJsonRedisSerializer {
@Override
public byte[] serialize(Object object) throws SerializationException {
if (object == null) {
return new byte[0];
}
//处理hash value 存储 无法执行自增 ERR hash value is not an integer
if (object instanceof Number) {
return JSON.toJSONBytes(object);
}
return super.serialize(object);
}
}
redis hash value ERR hash value is not an integer
于 2024-01-28 00:24:02 首次发布