当前位置:网站首页>Come on, handwritten RPC S2 serialization exploration
Come on, handwritten RPC S2 serialization exploration
2022-07-29 01:47:00 【In the misty rain of the Pavilion】
List of articles
SOA
Service Oriented Architecture (SOA) With the rapid development of the Internet A system architecture method . Service orientation is a design paradigm , Logical units for creating solutions , These logical units can be combined 、 Reusable , To support specific strategic goals and benefits of Service-oriented Computing .
( It feels like a micro service
Due to the split of many small service modules , Communication between modules is particularly important , Simple information transmission can be used MQ, Complex method calls must be robust RPC Support .
In actual production , We can't be like that in the last lesson , Just by “ Ask each other about the service name and method name offline ” The way to run our RPC function , We must have a completed system to ensure the health of the service . At least the following parts should be included :
- Service registry
- Service providers and related heartbeat detection mechanisms
- Stricter consumer calls 、 The ginseng 、 Exception handling mechanism
- Current limiting strategy
- Polling strategy, etc
The corresponding , The overall service process should be :
- The service provider starts the service , Register the service provider information to the service registry , Service provider information Generally, it includes the service host address 、 port 、 Service interface information, etc .
- The service consumer obtains the service provider information from the service registry to the local cache , At the same time, service consumption
Report the information of the applicant to the service registration center . - The service consumer selects a service provider to initiate service invocation according to a certain soft load policy , The service call First, adopt some data serialization scheme , Serialize the call data into an array of bytes that can be transmitted over the network , Adopt some NIO frame ( Such as Netty、 Mina、 Grizzy) Completion of invocation .
- Service governance ( Health monitoring 、 Current limiting the drop 、 Polling, etc )
Serialization and deserialization
Let's start with the most basic concepts .
serialize
serialize ( Serialization) It is the process of transforming the state information of an object into a form that can be stored or transmitted . in short , The process of converting an object into a sequence of bytes is called object serialization .
Deserialization
Deserialization ( Deserialization) It's the reverse of serialization . Deserialize a byte array into an object , The process of restoring a byte sequence to an object is called deserialization of the object .
sd The necessity of
- It enables the transmission of objects between systems that do not share memory and are connected through the network .
- Ensure that the transmission content is not distorted
Serialization instructions
- Serialization , Save only the state of the object , Regardless of the object's method .
- When a parent class implements serialization , Subclasses automatically implement serialization , You don't need to explicitly implement Serializable Interface .
- Call the instance variable of an object to reference other objects , When serializing the object, the reference object is also sequenced turn .
- When a field is declared as transient after , The default serialization mechanism ignores this field .
- For the above has been declared transient Yuduan of , Private methods can be added to classes writeObject() And readObject() Two methods to serialize .
Common serialization schemes
imitation Java Native serialization of
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/** * @Desc **/
public class MineSerializer {
public <T> byte[] serialize(T obj) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(obj);
objectOutputStream.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return byteArrayOutputStream.toByteArray();
}
@SuppressWarnings("unchecked")
public <T> T deserialize(byte[] data, Class<T> clazz) {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
try {
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
return (T) objectInputStream.readObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
XML and JSON serialize
JSON Serialization uses Alibaba fastjson,google Of gson All possible , Not much introduction . Here are XML serialize :
<dependencies>
<!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream -->
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.19</version>
</dependency>
</dependencies>
Code :
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import java.nio.charset.StandardCharsets;
/** * @Desc **/
public class MineXmlSerialize {
private static final XStream X_STREAM =new XStream(new DomDriver()) ;
public <T> byte[] serialize(T obj) {
return X_STREAM.toXML(obj).getBytes(StandardCharsets.UTF_8);
}
@SuppressWarnings("unchecked")
public <T> T deserialize(byte[] data, Class<T> clazz) {
String xml = new String(data);
return (T) X_STREAM.fromXML(xml);
}
}
Hessian serialize
Is a cross language binary serialization Protocol , Strong performance and easy to use , The most important is cross language .
<!-- https://mvnrepository.com/artifact/com.caucho/hessian -->
<dependency>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
<version>4.0.66</version>
</dependency>
Code :
import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
/** * @Desc **/
public class MineHessianSerialize {
public byte[] serialize(Object obj) {
if (obj == null) {
throw new NullPointerException();
}
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
HessianOutput ho = new HessianOutput(os);
ho.writeObject(obj);
return os.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public <T> T deserialize(byte[] data, Class<T> clazz) {
if (data == null) {
throw new NullPointerException();
}
try {
ByteArrayInputStream is = new ByteArrayInputStream(data);
HessianInput hi = new HessianInput(is);
return (T) hi.readObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Thrift serialize
Along with RPC Supporting serialization of the framework .
XML file :
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libfb303</artifactId>
<version>0.9.3</version>
</dependency>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.9.3</version>
</dependency>
Code
import org.apache.thrift.TBase;
import org.apache.thrift.TDeserializer;
import org.apache.thrift.TSerializer;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TBinaryProtocol.Factory;
/** * @Desc **/
public class MineThriftSerialize {
public <T> byte[] serialize(T obj) {
try {
if (!(obj instanceof TBase)) {
throw new UnsupportedOperationException("not support");
}
TSerializer serializer = new TSerializer(new Factory());
return serializer.serialize((TBase) obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public <T> T deserialize(byte[] data, Class<T> clazz) {
try {
if (!TBase.class.isAssignableFrom(clazz)) {
throw new UnsupportedOperationException("not support");
}
TBase o = (TBase) clazz.newInstance();
TDeserializer tDeserializer = new TDeserializer(new TBinaryProtocol.Factory());
tDeserializer.deserialize(o, data);
return (T) o;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
other
And Google protobuf, But it's troublesome to use, and it's basically useless for big projects
Serialization scheme selection
- Performance metrics ( Basic ratio of binary xml and json fast )
- Easy to use ruler ( It's not easy to learn )
- Cross language / Platform ruler ( such as go-nodejs-java-python framework )
- Long term support ( The parent company went bankrupt …)
边栏推荐
- 了解网址url的组成后 运用url模块、querystring模块和mime模块完善静态网站
- DSP震动座椅
- 【Web技术】1395- Esbuild Bundler HMR
- [hcip] MPLS Foundation
- About df['a column name'] [serial number]
- 规划数学期末模拟考试一
- Understand all the basic grammar of ES6 in one article
- Openpyxl merge cells
- How to protect WordPress website from network attack? It is essential to take safety measures
- Super scientific and technological data leakage prevention system, control illegal Internet behaviors, and ensure enterprise information security
猜你喜欢

Openpyxl cell center

第二轮Okaleido Tiger热卖的背后,是背后生态机构战略支持

Tomorrow infinite plan, 2022 conceptual planning scheme for a company's yuanuniverse product launch

Platofarm community ecological gospel, users can get premium income with elephant swap
![[hcip] experiment of republishing and routing strategy](/img/26/d62d3083796757d33c0a513f842176.png)
[hcip] experiment of republishing and routing strategy

AlphaFold揭示了蛋白质结构宇宙-从近100万个结构扩展到超过2亿个结构

瑞吉外卖项目实战Day01

我们总结了 3 大Nacos使用建议,并首次公开 Nacos 3.0 规划图 Nacos 开源 4 周年

SiC功率半导体产业高峰论坛成功举办

MySQL execution order
随机推荐
第二轮Okaleido Tiger热卖的背后,是背后生态机构战略支持
MySQL execution order
围绕新市民金融聚焦差异化产品设计、智能技术提效及素养教育
Six simple techniques to improve the value of penetration testing and save tens of thousands of yuan
规划数学期末模拟考试一
一文读懂Okaleido Tiger近期动态,挖掘背后价值与潜力
覆盖接入2w+交通监测设备,EMQ为深圳市打造交通全要素数字化新引擎
【golang】使用select {}
Event express | Apache Doris Performance Optimization Practice Series live broadcast course is open at the beginning. You are cordially invited to participate!
明日无限计划,2022某公司元宇宙产品发布会活动概念策划方案
【搜索】—— 迭代加深/双向DFS/IDA*
全面升级,淘宝/天猫api接口大全
SQL question brushing: find the last of all employees who have been assigned departments_ Name and first_ Name and Dept_ no
易观分析:以用户为中心,提升手机银行用户体验,助力用户价值增长
New upgrade: get Taobao product details "advanced version" API
瑞吉外卖项目实战Day01
Analysys analysis: focus on users, improve the user experience of mobile banking, and help the growth of user value
Pinduoduo can use many API interfaces
Super scientific and technological data leakage prevention system, control illegal Internet behaviors, and ensure enterprise information security
els 新的方块落下