package com.imyeyu.spring.util; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.SerializationException; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.io.IOException; import java.nio.charset.StandardCharsets; /** * Redis 序列化工具 * * @author 夜雨 * @version 2023-07-17 16:20 */ public class RedisSerializers { /** 工具类禁止实例化 */ private RedisSerializers() { } /** 字符串序列化 */ public static final StringRedisSerializer STRING = new StringRedisSerializer(); /** 长整型序列化 */ public static final RedisSerializer INTEGER = new RedisSerializer<>() { @Override public byte[] serialize(Integer value) throws SerializationException { if (value == null) { return null; } byte[] result = new byte[Integer.BYTES]; for (int i = Integer.BYTES - 1; 0 <= i; i--) { result[i] = (byte) (value & 0xFF); value >>= Byte.SIZE; } return result; } @Override public Integer deserialize(byte[] bytes) throws SerializationException { if (bytes == null) { return null; } int result = 0; for (int i = 0; i < Integer.BYTES; i++) { result <<= Byte.SIZE; result |= (bytes[i] & 0xFF); } return result; } }; /** 长整型序列化 */ public static final RedisSerializer LONG = new RedisSerializer<>() { @Override public byte[] serialize(Long value) throws SerializationException { if (value == null) { return null; } byte[] result = new byte[Long.BYTES]; for (int i = Long.BYTES - 1; 0 <= i; i--) { result[i] = (byte) (value & 0xFF); value >>= Byte.SIZE; } return result; } @Override public Long deserialize(byte[] bytes) throws SerializationException { if (bytes == null) { return null; } long result = 0; for (int i = 0; i < Long.BYTES; i++) { result <<= Byte.SIZE; result |= (bytes[i] & 0xFF); } return result; } }; /** * Json 序列化 * * @param 数据类型 * @param clazz 数据类型 * @return Redis 序列化器 */ public static RedisSerializer jacksonSerializer(Class clazz) { return new RedisSerializer<>() { private static final ObjectMapper JACKSON = new ObjectMapper(); @Override public byte[] serialize(T object) throws SerializationException { try { return JACKSON.writeValueAsString(object).getBytes(StandardCharsets.UTF_8); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } @Override public T deserialize(byte[] bytes) throws SerializationException { if (bytes == null) { return null; } try { return JACKSON.readValue(new String(bytes, StandardCharsets.UTF_8), clazz); } catch (IOException e) { throw new RuntimeException(e); } } }; } }