当前位置:网站首页>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
边栏推荐
- Uncaught reflectionexception: class view does not exist
- Pratique de l'attaque et de la défense du réseau HUST | 6 Expérience de sécurité du microprogramme de l'équipement IOT | expérience 2 technologie d'atténuation des attaques de l'équipement IOT basée s
- Leetcode 78. 子集 and 90. 子集 II
- Splicing full paths and uploading multiple pictures of laravel admin when laravel uses OSS
- PolarisMesh系列文章——概念系列(一)
- Wangeditor uploading local video modification
- 汇编语言(7)运算指令
- Apiccloud implements the document download and preview functions
- What should I do from member labels to portraits?
- What software is flush? Is online account opening safe?
猜你喜欢
![[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

leetcode 715. Range module (hard)

HUST network attack and defense practice | 6_ IOT device firmware security experiment | Experiment 2 MPU based IOT device attack mitigation technology

介绍一下实现建模中可能用到的时间序列预测之线性二次移动平均,Excel的简单操作

MQTT断开重连

How to calculate flops and params in deep learning

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

Nacos2.x.x start error creating bean with name 'grpcclusterserver';

10 years' experience in programmer career - for you who are confused

2021 q3-q4 investigation report on the use status of kotlin multiplatform
随机推荐
Splicing full paths and uploading multiple pictures of laravel admin when laravel uses OSS
The most complete kubernetes core command of the latest version so far
Nacos2.x.x start error creating bean with name 'grpcclusterserver';
Laravel admin hidden button, and set button display, default sequence, form form form non modifiable value
Is it safe to open an account in the top ten securities app rankings in China
Omnichannel membership - tmall membership 1: opening tutorial
[graduation season · advanced technology Er] I remember the year after graduation
Apiccloud implements the document download and preview functions
Introduction to the strongest swarm cluster one click deployment + hydrogen bomb level container management tool
【Redis 系列】redis 学习十六,redis 字典(map) 及其核心编码结构
4. N queen problem
Seven major trends deeply affecting the U.S. consumer goods industry in 2022
PC QQ大廳 上傳更新 修改versionInfo
One click deployment of your own community forum
Leetcode 78. 子集 and 90. 子集 II
Dynamic programming to solve stock problems (Part 2)
.net中,日志组件 Nlog,SerialLog, Log4Net的用法
动态规划解决股票问题(下)
PC QQ hall upload update modify VersionInfo
Prospering customs through science and technology, Ronglian and Tianjin Customs jointly build a genomic database and analysis platform