package com.farriver.bwf.common.utilities; import com.alibaba.fastjson2.JSON; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.SerializationException; import org.springframework.util.Assert; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; public class FastJson2JsonRedisSerializer implements RedisSerializer { private final Logger logger = LoggerFactory.getLogger(FastJson2JsonRedisSerializer.class); private ObjectMapper objectMapper = new ObjectMapper(); public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; private final Class clazz; static { // ParserConfig.getGlobalInstance().setAutoTypeSupport(true); // 如果遇到反序列化autoType is not support错误,请添加并修改一下包名到bean文件路径 // ParserConfig.getGlobalInstance().addAccept("com.farriver.oqb.data.model"); } public FastJson2JsonRedisSerializer(Class clazz) { super(); this.clazz = clazz; } public byte[] serialize(T t) throws SerializationException { if (t == null) { return new byte[0]; } return JSON.toJSONString(t).getBytes(DEFAULT_CHARSET); } public T deserialize(byte[] bytes) throws SerializationException { if (bytes == null || bytes.length <= 0) { return null; } String str = new String(bytes, DEFAULT_CHARSET); return JSON.parseObject(str, clazz); } public void setObjectMapper(ObjectMapper objectMapper) { Assert.notNull(objectMapper, "'objectMapper' must not be null"); this.objectMapper = objectMapper; } protected JavaType getJavaType(Class clazz) { return TypeFactory.defaultInstance().constructType(clazz); } }