motan源码分析七:序列化

motan源码分析七:序列化motan 的序列化支持两种协议 一种是 json 另一种是 hessian2 主要涉及到的类和接口是是 FastJsonSeri Hessian2Seri Serializatio Codec AbstractCode NettyDecoder NettyEncoder DefaultRpcCo 和 CompressRpcC 等 1 FastJs

motan的序列化支持两种协议,一种是json,另一种是hessian2。主要涉及到的类和接口是是:FastJsonSerialization、Hessian2Serialization、Serialization、Codec、AbstractCodec、NettyDecoder、NettyEncoder、DefaultRpcCodec和CompressRpcCodec等。

1.FastJsonSerialization使用json作为数据交换协议,Hessian2Serialization使用hessian2作为数据交换协议

复制代码
@SpiMeta(name = "hessian2") public class Hessian2Serialization implements Serialization { @Override public byte[] serialize(Object data) throws IOException {//使用hessan2进行序列化 ByteArrayOutputStream bos = new ByteArrayOutputStream(); Hessian2Output out = new Hessian2Output(bos); out.writeObject(data); out.flush(); return bos.toByteArray(); } @SuppressWarnings("unchecked") @Override public 
  
    T deserialize( 
   byte[] data, Class 
   
     clz) 
    throws 
     IOException {//使用hessan2进行反序列化 Hessian2Input input = 
    new Hessian2Input( 
    new 
     ByteArrayInputStream(data));  
    return 
     (T) input.readObject(clz); } } 
    
  
复制代码

 

2.motan支持压缩和非压缩两种方式

复制代码
 public byte[] encode(Channel channel, Object message) throws IOException { if (needEncodeV1(message)) {//判断使用哪个版本的encode,decode同样 return v1Codec.encode(channel, message); } else { // 使用v2压缩版本 return encodeV2(channel, message);//使用压缩版本的encode } } public byte[] encodeV2(Channel channel, Object message) throws IOException { try { if (message instanceof Request) { return encodeRequest(channel, (Request) message);//序列化并压缩request对象 } else if (message instanceof Response) { return encodeResponse(channel, (Response) message);//序列化并压缩response对象 } } catch (Exception e) { if (ExceptionUtil.isMotanException(e)) { throw (RuntimeException) e; } else { throw new MotanFrameworkException("encode error: isResponse=" + (message instanceof Response), e, MotanErrorMsgConstant.FRAMEWORK_ENCODE_ERROR); } } throw new MotanFrameworkException("encode error: message type not support, " + message.getClass(), MotanErrorMsgConstant.FRAMEWORK_ENCODE_ERROR); } private byte[] encodeRequest(Channel channel, Request request) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput output = createOutput(outputStream); addMethodInfo(output, request); //拿到hessian2或fasjson处理对象 Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension( channel.getUrl().getParameter(URLParamType.serialize.getName(), URLParamType.serialize.getValue())); if (request.getArguments() != null && request.getArguments().length > 0) { for (Object obj : request.getArguments()) { serialize(output, obj, serialization);//序列化 } } if (request.getAttachments() == null || request.getAttachments().isEmpty()) { // empty attachments output.writeShort(0); } else { // 需要copy一份attachment进行签名替换,这样在失败重试时原始的request信息不会变更 Map 
  
    attachments = 
    copyMap(request.getAttachments()); replaceAttachmentParamsBySign(channel, attachments); addAttachment(output, attachments); } output.flush();  
   byte[] body = 
    outputStream.toByteArray();  
   byte flag = 
    MotanConstants.FLAG_REQUEST; output.close(); Boolean usegz = 
    channel.getUrl().getBooleanParameter(URLParamType.usegz.getName(), URLParamType.usegz.getBooleanValue());  
   int minGzSize = 
    channel.getUrl().getIntParameter(URLParamType.mingzSize.getName(), URLParamType.mingzSize.getIntValue());  
   return 
    encode(compress(body, usegz, minGzSize), flag, request.getRequestId());//压缩处理 } 
  
复制代码

 

3.通过NettyDecoder和NettyEncoder与netty框架进行结合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
protected 
Object encode(ChannelHandlerContext ctx, Channel nettyChannel, Object message) 
throws 
Exception {
     
    
long 
requestId = getRequestId(message);
//获取requestId
    
byte
[] data = 
null
;
     
    
if 
(message 
instanceof 
Response) {
        
try 
{
            
data = codec.encode(client, message);
        

catch 
(Exception e) {
            
LoggerUtil.error(
"NettyEncoder encode error, identity=" 
+ client.getUrl().getIdentity(), e);
            
Response response = buildExceptionResponse(requestId, e);
            
data = codec.encode(client, response);
        
}
    

else 
{
        
data = codec.encode(client, message);
//调用DefaultRpcCodec或压缩的codec来编码
    
}
 
    
byte
[] transportHeader = 
new 
byte
[MotanConstants.NETTY_HEADER];
    
ByteUtil.short2bytes(MotanConstants.NETTY_MAGIC_TYPE, transportHeader, 
0
);
    
transportHeader[
3
] = getType(message);
    
ByteUtil.long2bytes(getRequestId(message), transportHeader, 
4
);
    
ByteUtil.int2bytes(data.length, transportHeader, 
12
);
 
    
return 
ChannelBuffers.wrappedBuffer(transportHeader, data);
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/224171.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月17日 下午12:33
下一篇 2026年3月17日 下午12:33


相关推荐

  • 一文读懂扣子(Coze)常用组件:节点&大模型&插件详解

    一文读懂扣子(Coze)常用组件:节点&大模型&插件详解

    2026年3月12日
    5
  • Werkzeug学习笔记

    Werkzeug学习笔记useragent模块UserAgent(ua:str)#ua测试字符串ua=’Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/60.0.3112.101Safari/537.36’#实例化user_

    2022年10月7日
    5
  • webservices原理

    webservices原理nbsp nbsp nbsp nbsp nbsp nbsp 无论是在计算机杂志还是在 Internet 上 目前最热门的话题莫过于 WebServices 各个平台之间的锋争 各个新产品的发布 众多新标准的制订 大都和 WebServices 有关 nbsp WebServices 的起源 Web 应用的巨大成功和不断发展 使其渗透到商业领域和个人生活的各个方面 人们只要使用浏览器 就可以享受到各种各样的 Web 服务 例如网上购物 网上交易 网络游戏

    2026年3月17日
    2
  • document.documentElement.clientWidth

    document.documentElement.clientWidth关于获取各种浏览器可见窗口大小的一点点研究functiongetInfo(){vars=””;s=”网页可见区域宽:”document.body.clientWidth;s=”网页可见区域高:”document.body.clientHeight;s=”网页可见区域宽:”document.body.offsetWidth”(包括边线和滚动

    2022年7月22日
    15
  • pp图与qq图_画图python

    pp图与qq图_画图python统计学中有时会会用到PP图或QQ图

    2022年8月10日
    35
  • 华为论坛官网_华为设备官网

    华为论坛官网_华为设备官网今日看点✦华为将持续投入汽车行业,今年研发投资将达10亿美元✦绿地集团旗下绿地数科拟2023年前上市,利润达到60亿元✦瑞幸首家咖啡烘焙基地正式投产,总投资2.1亿元✦海南离岛免税…

    2022年10月5日
    5

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号