当前位置:网站首页>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
边栏推荐
- Redux related usage
- Is it safe to open a stock account by mobile phone
- In depth understanding of STM32 serial port experiment (register) [nanny level tutorial]
- Lintcode 130 · 堆化
- ctfshow web入门 命令执行web75-77
- 18: Chapter 3: development of pass service: 1: SMS login & registration process, introduction; (SMS verification code is used here)
- (typora picture bed) Alibaba cloud OSS building picture bed +picgo uploading picture detailed tutorial
- Omnichannel membership - tmall membership 2: frequently asked questions
- What should I do from member labels to portraits?
- 开通证券账户需要注意事项 开户安全吗
猜你喜欢

Flannel's host GW and calico

Machine learning SVM - Experimental Report

MQTT断开重连

. Net, the usage of log components NLog, seriallog, log4net

Prospering customs through science and technology, Ronglian and Tianjin Customs jointly build a genomic database and analysis platform

How to prevent weight loss under Gao Bingfa?
女性科学家的流失

统计遗传学:第一章,基因组基础概念
![[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure](/img/d5/db1931596c26090092aaa065103dbb.png)
[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure

有手就行的移动平均法、指数平滑法的Excel操作,用来时间序列预测
随机推荐
高并发下如何防重?
NFS共享存储服务安装
Is it safe to open an account in the top ten securities app rankings in China
FasterRCNN
10 years' experience in programmer career - for you who are confused
Flannel's host GW and calico
Member system + enterprise wechat + applet to help the efficient transformation of private domain
TCP interview
What software is flush? Is online account opening safe?
Laravel admin obtains non auto increment ID and submits hidden forms
女性科学家的流失
基于slate构建文档编辑器
Machine learning LDA - Experimental Report
初探Protostuff的使用[通俗易懂]
Cet article présente la moyenne mobile quadratique linéaire et le fonctionnement simple d'Excel pour réaliser la prédiction des séries chronologiques dans la modélisation.
Group by is used in laravel to group and query the quantity
Random numbers in leetcode 710 blacklist [random numbers] the leetcode path of heroding
FasterRCNN
Nacos2.x.x start error creating bean with name 'grpcclusterserver';
利用 Repository 中的方法解决实际问题