netty编解码之jboss marshalling


jboss marshalling是jboss内部的一个序列化框架,速度也十分快,这里netty也提供了支持,使用十分方便,不需要像protobuf一样编写proto文件,只需要提供两个编解码器即可,以下就是jboss marshalling使用的开始。

源码程序


model类


model类和之前编写java序列化的时候没有区别,这里便不再多说,仅仅贴出源码:

SubscribeReq:

package cn.com.serialize;import java.io.Serializable;/*** Created by xiaxuan on 17/11/27.*/
public class SubscribeReq implements Serializable {private int subReqID;private String userName;private String productName;private String phoneNumber;private String address;//getter setter...@Overridepublic String toString() {return "SubscribeReq{" +"subReqID=" + subReqID +", userName='" + userName + '\'' +", productName='" + productName + '\'' +", phoneNumber='" + phoneNumber + '\'' +", address='" + address + '\'' +'}';}
}

SubscribeResp:

package cn.com.serialize;import java.io.Serializable;/*** Created by xiaxuan on 17/11/27.*/
public class SubscribeResp implements Serializable {private int subReqID;private int respCode;private String desc;//getter setter...@Overridepublic String toString() {return "SubscribeResp{" +"subReqID=" + subReqID +", respCode=" + respCode +", desc='" + desc + '\'' +'}';}
}

marshalling编解码工厂类


MarshallingCodeCFactory:

package cn.com.marshalling;import io.netty.handler.codec.marshalling.*;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;/*** Created by xiaxuan on 17/11/28.*/
public final class MarshallingCodeCFactory {public static MarshallingDecoder buildMarshallingDecoder() {final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");final MarshallingConfiguration configuration = new MarshallingConfiguration();configuration.setVersion(5);UnmarshallerProvider provider = new DefaultUnmarshallerProvider(marshallerFactory, configuration);MarshallingDecoder decoder = new MarshallingDecoder(provider, 1024);return decoder;}public static MarshallingEncoder buildMarshallingEncoder() {final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");final MarshallingConfiguration configuration = new MarshallingConfiguration();configuration.setVersion(5);MarshallerProvider provider = new DefaultMarshallerProvider(marshallerFactory, configuration);MarshallingEncoder encoder = new MarshallingEncoder(provider);return encoder;}
}

这里在获取factory的时候传入的参数为serial表示为创建java序列化工厂对象。
在创建MarshallingDecoder对象时传入两个参数,分别是UnmarshallerProvider和单个消息序列化后的最大长度。

server程序


SubReqServer:

package cn.com.marshalling;import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;/*** Created by xiaxuan on 17/11/28.*/
public class SubReqServer {public void bind(int port) {//配置服务端NIO线程组EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());ch.pipeline().addLast(new SubReqServerHandler());}});//绑定端口,同步等待成功ChannelFuture f = b.bind(port).sync();//等待服务端监听端口关闭f.channel().closeFuture().sync();} catch (InterruptedException e) {e.printStackTrace();} finally {//优雅退出bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}public static void main(String[] args) {int port = 8080;new SubReqServer().bind(port);}
}

这里我们将先前MarshallingFactory工厂类创建的MarshallingDecoder解码器和MarshallingEncoder编码器加入到ChannelPipline中,来进行对我们的传输对象进行编解码。

SubReqServerHandler

package cn.com.marshalling;import cn.com.serialize.SubscribeReq;
import cn.com.serialize.SubscribeResp;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;@Sharable
public class SubReqServerHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {SubscribeReq req = (SubscribeReq) msg;if ("Xiaxuan".equalsIgnoreCase(req.getUserName())) {System.out.println("Service accept client subscrib req : ["+ req.toString() + "]");ctx.writeAndFlush(resp(req.getSubReqID()));}}private SubscribeResp resp(int subReqID) {SubscribeResp resp = new SubscribeResp();resp.setSubReqID(subReqID);resp.setRespCode(0);resp.setDesc("Netty book order succeed, 3 days later, sent to the designated address");return resp;}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {cause.printStackTrace();ctx.close();// 发生异常,关闭链路}
}

业务逻辑与之前并没有太多不同,均是获取到客户端请求后进行响应。

client程序


SubReqClient

package cn.com.marshalling;import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;/*** Created by xiaxuan on 17/12/5.*/
public class SubReqClient {public void connect(int port, String host) {EventLoopGroup group = new NioEventLoopGroup();try {Bootstrap b = new Bootstrap();b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());ch.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());ch.pipeline().addLast(new SubReqClientHandler());}});//发起异步连接操作ChannelFuture f = b.connect(host, port).sync();//等待客户端链路关闭f.channel().closeFuture().sync();} catch (InterruptedException e) {e.printStackTrace();} finally {group.shutdownGracefully();}}public static void main(String[] args) {int port = 8080;String host = "127.0.0.1";new SubReqClient().connect(port, host);}
}

除了编解码框架以外,其他的并没有不同的。

SubReqClientHandler:

package cn.com.marshalling;import cn.com.serialize.SubscribeReq;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;public class SubReqClientHandler extends ChannelInboundHandlerAdapter {public SubReqClientHandler() {}@Overridepublic void channelActive(ChannelHandlerContext ctx) {for (int i = 0; i < 10; i++) {ctx.write(subReq(i));}ctx.flush();}private SubscribeReq subReq(int i) {SubscribeReq req = new SubscribeReq();req.setAddress("NanJing YuHuaTai");req.setPhoneNumber("135xxxxxxxx");req.setProductName("Netty Book For Marshalling");req.setSubReqID(i);req.setUserName("Xiaxuan");return req;}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {System.out.println("Receive server response : [" + msg + "]");}@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {ctx.flush();}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {cause.printStackTrace();ctx.close();}
}

客户端业务逻辑与之前也没有其他的区别,都是构建十次请求,然后一次性发出,最后输出服务端的响应。

程序运行


分别启动server程序和client程序,查看运行结果,如下:

server:

client:

运行成功。

使用jboss marshalling来进行编解码还是比较简单的,在这里我们模拟了TCP的粘包/拆包场景,但是程序的运行结果仍然正确,说明Marshalling的编解码器支持半包和粘包的处理,对于普通的开发者来说,只需要将Marshalling编码器和解码器加入到ChannelPipline中,就能实现对Marshalling序列化的支持。

netty编解码之jboss marshalling相关推荐

  1. Netty系列之Netty编解码框架分析

    1. 背景 1.1. 编解码技术 通常我们也习惯将编码(Encode)称为序列化(serialization),它将对象序列化为字节数组,用于网络传输.数据持久化或者其它用途. 反之,解码(Decod ...

  2. Netty编解码,粘包拆包及零拷贝

    Netty编解码 Netty涉及到编解码的组件有Channel.ChannelHandler.ChannelPipe等,先大概了解下这几个组件的作用. ChannelHandler ChannelHa ...

  3. 深入理解Netty编解码、粘包拆包、心跳机制

    点赞再看,养成习惯,公众号搜一搜[一角钱技术]关注更多原创技术文章. 本文 GitHub org_hejianhui/JavaStudy 已收录,有我的系列文章. 前言 BIO .NIO .AIO 总 ...

  4. Netty编解码及protostuff

    Netty编解码是什么? 要想了解编解码,首先要知客户端和服务端是怎么处理信息的,当通过Netty发送或者接收信息的时候,首先要将接收到的消息尽心decode()方法进行解码,然后发送ChannelP ...

  5. Netty详解(六):Netty 编解码技术

    1. 概述 基于Java提供的对象输入/输出流ObjectInputStream和ObjectOutputStream,可以直接把Java对象作为可村粗的字节数组写入文件,也可以传输到网络上去.Jav ...

  6. Netty详解(七):Netty 编解码以及消息头编解码器

    1. MessagePack 概述 MessagePack是一个高效的二进制序列化框架,像JSON一样支持不同语言间的数据交换,速度更快,序列化之后的码流更小. MessagePacke优点 编解码高 ...

  7. TCP 粘包半包 netty 编解码 三者关系

    1 何为粘包 / 半包? 对方一次性接收了多条消息这种现象,我们就称之为 粘包现象. 对方多次接收了不完整消息这种现象,我们就称之为 半包现象. 粘包的原因: 发送方发送的消息 < 缓冲区大小 ...

  8. JBoss Marshalling编解码

    一.简介 JBoss Marshalling是一个Java对象序列化包,对JDK默认的序列化框架进行了优化,但又保持和java.io.Serializable接口的兼容. 二.Marshalling开 ...

  9. Netty之编解码技术(四)

    通常我们习惯将编码(Encode)称为序列化(serialization),它将对象序列化为字节数组,用于网络传输.数据持久化或者其它用途. 反之,解码(Decode)称为反序列化(deseriali ...

  10. Netty(十四)(中级篇)MessagePack编解码

    一,客户端 假如你现在还在为自己的技术担忧,假如你现在想提升自己的工资,假如你想在职场上获得更多的话语权,假如你想顺利的度过35岁这个魔咒,假如你想体验BAT的工作环境,那么现在请我们一起开启提升技术 ...

最新文章

  1. 删掉java影响什么_java带来的影响
  2. FreeBSD8.0搭建Apache+PHP+MySql平台
  3. 认识 UART 接口
  4. java生产者与消费者问题_java生产者与消费者问题
  5. 前端学习(2569):如何跨组件调用实例
  6. 戴尔-EMC将至强Phi服务器与Tesla GPU纳入PowerEdge
  7. 关于oracle自动编号
  8. PCM音频数据格式介绍
  9. java jsp中文乱码怎么解决_如何解决JSP中文乱码问题
  10. Amesim2016与Matlab2017b联合仿真环境搭建
  11. OneNote 提示不能使用个人账户登录( 亲测可用)
  12. 据我所知目前就只飞秋表情库
  13. video Station 支持字幕格式
  14. css背景立变立体感
  15. stm32 步进电机控制,S曲线加减速,匀加速运动
  16. 极品特效HTML5动画推荐,不看的程序员后悔一辈子
  17. Tuscany SCA软件架构设计理念分析鉴赏 (一)
  18. 你可能没注意的CSS单位 BY:色拉油啊油
  19. 7.读写HBase数据(华为云学习笔记,Spark编程基础,大数据)
  20. 【安全牛学习笔记】密码嗅探

热门文章

  1. Little Dima and Equation
  2. 在线遥感影像与地图集数据下载搜集
  3. oracle11g64为的安装,PLSQL Developer连接不上Win7 64为系统下安装的Oracle11g64位的解决办法...
  4. fatal: unable to auto-detect email address (got ‘...@...(none)‘)
  5. python生成vcf通讯录文件
  6. 红米note5解锁教程_红米Note5人脸解锁怎么设置 红米Note5人脸解锁设置教程
  7. 中秋闲来无事,自己写个2048玩玩
  8. Emscripten 单词_背单词分享 | 我觉得实用的背单词方法
  9. Win10下次使用debug进入DOS进行汇编开发
  10. Exploiting Deep Generative Prior for Versatile Image Restoration and Manipulation