当前位置:网站首页>On the use of protostaff [easy to understand]
On the use of protostaff [easy to understand]
2022-06-26 11:55:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
On Protostuff Use
Studying recently RPC, I saw a man called Protostuff The library of , It's based on Google Protocal Buffer Serialization Library , I've seen it before Protocol Buffer, Yes, after learning some materials , Wrote a demo, recorded .
What is? Protocol Buffer?
Protocol Buffer It is a data exchange format produced by Google , Language and platform independent , Be similar to json.Google Provides the implementation of multiple languages :java、c++、go and python. Object serialization Protocol Buffer After that, the readability is poor , But compared to the xml,json, It takes up less , Fast . Suitable for data storage or RPC Data exchange format .
Java Serialization Library – Protostuff
Compared with our common json Come on ,Protocol Buffer The threshold is higher , Because I need to write .proto file , Then compile it into the target language , This is very troublesome to use . But now with protostuff after , You don't need to rely on .proto The file , He can speak directly to POJO Serialization and deserialization , It's very simple to use .
actual combat
Create a new one SpringBoot Project , To introduce Protostuff Dependence
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>${protostuff.version}</version>
</dependency>
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>${protostuff.version}</version>
</dependency>First write two POJO, Then nest them , It's used here lombok Of @Data Notes and @Builder annotation ,@Data Can be generated automatically getter setter,@Builder Annotations allow us to create objects through more elegant builder patterns .
@Data
@Builder
public class User {
private String id;
private String name;
private Integer age;
private String desc;
}@Data
@Builder
public class Group {
private String id;
private String name;
private User user;
}Next write Protostuff Serialization tool class
public class ProtostuffUtils {
/** * Avoid reapplying every time you serialize Buffer Space */
private static LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
/** * cache Schema */
private static Map<Class<?>, Schema<?>> schemaCache = new ConcurrentHashMap<>();
/** * Serialization method , Serializes the specified object into a byte array * * @param obj * @param <T> * @return */
@SuppressWarnings("unchecked")
public static <T> byte[] serialize(T obj) {
Class<T> clazz = (Class<T>) obj.getClass();
Schema<T> schema = getSchema(clazz);
byte[] data;
try {
data = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} finally {
buffer.clear();
}
return data;
}
/** * Deserialization method , Deserialize the byte array to the specified Class type * * @param data * @param clazz * @param <T> * @return */
public static <T> T deserialize(byte[] data, Class<T> clazz) {
Schema<T> schema = getSchema(clazz);
T obj = schema.newMessage();
ProtostuffIOUtil.mergeFrom(data, obj, schema);
return obj;
}
@SuppressWarnings("unchecked")
private static <T> Schema<T> getSchema(Class<T> clazz) {
Schema<T> schema = (Schema<T>) schemaCache.get(clazz);
if (Objects.isNull(schema)) {
// This schema adopt RuntimeSchema Create and cache
// So you can always call RuntimeSchema.getSchema(), This method is thread safe
schema = RuntimeSchema.getSchema(clazz);
if (Objects.nonNull(schema)) {
schemaCache.put(clazz, schema);
}
}
return schema;
}
}Verify serialization function
@SpringBootApplication
public class Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... strings) throws Exception {
// Create a user object
User user = User.builder().id("1").age(20).name(" Zhang San ").desc("programmer").build();
// Create a Group object
Group group = Group.builder().id("1").name(" grouping 1").user(user).build();
// Use ProtostuffUtils serialize
byte[] data = ProtostuffUtils.serialize(group);
System.out.println(" After serialization :" + Arrays.toString(data));
Group result = ProtostuffUtils.deserialize(data, Group.class);
System.out.println(" After deserialization :" + result.toString());
}
}You can see that the console prints out the following data , Description serialization and deserialization succeeded
After serialization :[10, 1, 49, 18, 7, -27, -120, -122, -25, -69, -124, 49, 27, 10, 1, 49, 18, 6, -27, -68, -96, -28, -72, -119, 24, 20, 34, 10, 112, 114, 111, 103, 114, 97, 109, 109, 101, 114, 28]
After deserialization :Group(id=1, name= grouping 1, user=User(id=1, name= Zhang San , age=20, desc=programmer))Last , The code is here Address , welcome star.
Reference resources
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/133960.html Link to the original text :https://javaforall.cn
边栏推荐
- Openresty overview
- HUST網絡攻防實踐|6_物聯網設備固件安全實驗|實驗二 基於 MPU 的物聯網設備攻擊緩解技術
- TCP面试
- express在nodejs中的基本使用
- Ctfshow web getting started command execution web75-77
- 哈希表的前置知识---二叉搜索树
- loggie 编码以及换行符测试
- The transformation of enterprise customers' digital assets needs to suit the case
- Loggie encoding and newline character test
- APICloud 实现文档下载和预览功能
猜你喜欢

MQTT断开重连
![[graduation season · advanced technology Er] I remember the year after graduation](/img/e7/8e1dafa561217b77a3e3992977a8ec.png)
[graduation season · advanced technology Er] I remember the year after graduation

FasterRCNN

科技兴关,荣联与天津海关共建基因组数据库及分析平台

高并发下如何防重?

HUST network attack and defense practice | 6_ IOT device firmware security experiment | Experiment 3 freertos-mpu protection bypass

This paper introduces the simple operation of realizing linear quadratic moving average of time series prediction that may be used in modeling and excel

.net中,日志组件 Nlog,SerialLog, Log4Net的用法

国际美妆业巨头押注中国

HUST网络攻防实践|6_物联网设备固件安全实验|实验三 FreeRTOS-MPU 保护绕过
随机推荐
Common problems and Thoughts on member operation management
TCP interview
AD - 将修改后的 PCB 封装更新到当前 PCB 中
This paper introduces the simple operation of realizing linear quadratic moving average of time series prediction that may be used in modeling and excel
18:第三章:开发通行证服务:1:短信登录&注册流程,简介;(这儿使用短信验证码)
FastRCNN
介紹一下實現建模中可能用到的時間序列預測之線性二次移動平均,Excel的簡單操作
Omnichannel membership - tmall membership 2: frequently asked questions
Black squares in word
In depth understanding of STM32 serial port experiment (register) [nanny level tutorial]
有手就行的移动平均法、指数平滑法的Excel操作,用来时间序列预测
I'd like to know what preferential activities are available for stock account opening? Is it safe to open an account online?
Statistical genetics: Chapter 1, basic concepts of genome
Mqtt disconnect and reconnect
18: Chapter 3: development of pass service: 1: SMS login & registration process, introduction; (SMS verification code is used here)
[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure
UDP协议详解[通俗易懂]
HUST網絡攻防實踐|6_物聯網設備固件安全實驗|實驗二 基於 MPU 的物聯網設備攻擊緩解技術
HUST网络攻防实践|6_物联网设备固件安全实验|实验二 基于 MPU 的物联网设备攻击缓解技术
leetcode 715. Range module (hard)