Initial project

This commit is contained in:
Timi
2025-07-08 14:34:32 +08:00
parent 271e2ae673
commit c27146aa91
56 changed files with 3050 additions and 80 deletions

View File

@@ -0,0 +1,99 @@
package com.imyeyu.spring.util;
import com.google.gson.Gson;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.nio.charset.StandardCharsets;
/**
* @author 夜雨
* @version 2023-07-17 16:20
*/
public class RedisSerializers {
/** 字符串序列化 */
public static final StringRedisSerializer STRING = new StringRedisSerializer();
/** 长整型序列化 */
public static final RedisSerializer<Integer> 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> 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;
}
};
/** Gson 序列化 */
public static <T> RedisSerializer<T> gsonSerializer(Class<T> clazz) {
return new RedisSerializer<>() {
private static final Gson GSON = new Gson();
@Override
public byte[] serialize(T object) throws SerializationException {
return GSON.toJson(object).getBytes(StandardCharsets.UTF_8);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null) {
return null;
}
return GSON.fromJson(new String(bytes, StandardCharsets.UTF_8), clazz);
}
};
}
}