Java序列化之ProtoStuff
知识点:
- ProtoStuff 是将结构数据转为字节流进行序列化的,优点是占用空间小,速度快,缺点是可读性差。
- ProtoStuff 是基于 ProtoBuf 发展而来的。
本文不讲那么多背景,直接上代码:
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
public class ProtostuffRedisSerializer implements RedisSerializer<Object> {
private static final Schema<ObjectWrapper> SCHEMA = RuntimeSchema.getSchema(ObjectWrapper.class);
@Override
public byte[] serialize(Object o) throws SerializationException {
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
byte[] bytes;
try {
bytes = ProtostuffIOUtil.toByteArray(new ObjectWrapper(o), SCHEMA, buffer);
} finally {
buffer.clear();
}
return bytes;
}
@Override
public Object deserialize(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return null;
}
ObjectWrapper wrapper = new ObjectWrapper();
ProtostuffIOUtil.mergeFrom(bytes, wrapper, SCHEMA);
return wrapper.getObject();
}
@Override
public boolean canSerialize(Class<?> type) {
return false;
}
@Override
public Class<?> getTargetType() {
return null;
}
public static class ObjectWrapper {
private Object object;
public ObjectWrapper() {
}
public ObjectWrapper(Object object) {
this.object = object;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
}
在RedisTemplate上使用:
private static final String PROTOSTUFF_REDIS_TEMPLATE = "protostuffRedisTemplate";
@Bean(name = PROTOSTUFF_REDIS_TEMPLATE)
public RedisTemplate<String, Object> protostuffRedisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
template.setKeySerializer(redisSerializer);
template.setHashKeySerializer(redisSerializer);
ProtostuffRedisSerializer protostuffRedisSerializer = new ProtostuffRedisSerializer();
template.setValueSerializer(protostuffRedisSerializer);
template.setHashValueSerializer(protostuffRedisSerializer);
template.afterPropertiesSet();
return template;
}
参考:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律