當進行遠程跨進程服務調用時,需要把被傳輸的Java對象編碼爲字節數組或者ByteBuffer對象。而當遠程服務讀取到ByteBuffer對象或者字節數組時,需要將其解碼爲發送時的Java對象。這被稱爲Java對象編解碼技術。而我們常見得Java序列化僅僅是Java編解碼技術的一種,由於java序列化有以下缺點:
- 無法跨語言
- 序列化後的碼流太大
- 序列化性能太低
因此衍生了多種編解碼技術和框架。
如何評判一個編解碼框架的優劣
- 是否支持跨語言,支持的語言種類是否豐富
- 編碼後的碼流大小
- 編解碼的性能
- 類庫是否小巧,API使用是否方便
- 使用者需要手工開發的工作量和難度
在同等情況下,編碼後的字節數組越大,存儲的時候就越佔空間,存儲的硬件成本就越高,並且在網絡傳輸時更佔帶寬,導致系統的吞吐量降低。
業界主流的編解碼框架
- Google的Protobuf
- Facebook的Thrift
- JBoss Marshalling
後面會介紹以上三個編解碼框架的使用。
MessagePack編解碼
MessagePack的特點:
- 編解碼高效,性能高
- 序列化之後的碼流小
- 支持跨語言
使用
如果是使用Maven開發,先添加依賴:
<dependencies>
...
<dependency>
<groupId>org.msgpack</groupId>
<artifactId>msgpack</artifactId>
<version>${msgpack.version}</version>
</dependency>
...
</dependencies>
api使用:
// Create serialize objects.
List<String> src = new ArrayList<String>();
src.add("msgpack");
src.add("kumofs");
src.add("viver");
MessagePack msgpack = new MessagePack();
// Serialize
byte[] raw = msgpack.write(src);
// Deserialize directly using a template
List<String> dst1 = msgpack.read(raw, Templates.tList(Templates.TString));
System.out.println(dst1.get(0));
System.out.println(dst1.get(1));
System.out.println(dst1.get(2));
在Netty中使用實踐
編碼器開發
編碼器MsgpackEncoder繼承MessageToByteEncoder,負責將Object類型的POJO對象編碼爲byte數組,然後寫入到ByteBuf中。
package com.ph.Netty;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.msgpack.MessagePack;
/**
* msg編碼器
* Create by PH on 2018/11/7
*/
public class MsgpackEncoder extends MessageToByteEncoder<Object> {
/**
*
* @param arg0
* @param arg1 要發送的對象
* @param arg2 發送緩衝區
* @throws Exception
*/
protected void encode(ChannelHandlerContext arg0, Object arg1, ByteBuf arg2) throws Exception {
MessagePack msgpack = new MessagePack();
byte[] raw = msgpack.write(arg1);
arg2.writeBytes(raw);
}
}
解碼器開發
package com.ph.Netty;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.msgpack.MessagePack;
import java.util.List;
/**
* MessagePack解碼器
* Create by PH on 2018/11/7
*/
public class MsgpackDecoder extends MessageToMessageDecoder<ByteBuf> {
/**
*
* @param arg0
* @param arg1 接受到的數據
* @param arg2 解碼後的數據
* @throws Exception
*/
protected void decode(ChannelHandlerContext arg0, ByteBuf arg1, List<Object> arg2) throws Exception {
final int length = arg1.readableBytes();
final byte[] array = new byte[length];
//獲取要解碼的byte數組
arg1.getBytes(arg1.readerIndex(), array, 0, length);
MessagePack msgpack = new MessagePack();
//將解碼後的對象加入到解碼列表中
arg2.add(msgpack.read(array));
}
}
首先從數據報arg1中獲取需要解碼的byte數組,然後調用MessagePack的read方法將其反序列化爲Object對象,將解碼後的對象加入到解碼列表arg2中。
需要序列化的POJO類
注意需要加上@Message註解。
package com.ph.Netty;
import org.msgpack.annotation.Message;
/**
* Create by PH on 2018/11/7
*/
@Message
public class UserInfo {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
LengthFieldPrepender和LengthFieldBasedFrameDecoder介紹
爲了防止粘包/半包,除了之前介紹的解決策略外,其實最常用的是在消息頭中新增報文長度字段,利用該字段進行半包的編解碼。詳細說明看這裏
Netty服務端
package com.ph.Netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
/**
* Create by PH on 2018/11/7
*/
public class NettyServer {
public static void main(String[] args) throws Exception {
int port = 8080;
if(args !=null && args.length>0) {
try {
port = Integer.valueOf(args[0]);
}catch (NumberFormatException e) {
//採用默認值
}
}
new NettyServer().bind(port);
}
public void bind(int port) throws Exception{
//NioEventLoopGroup是一個線程組,包含了一組NIO線程,專門用於網絡事件的處理,實際上他們就是Reactor線程組
//bossGroup僅接收客戶端連接,不做複雜的邏輯處理,爲了儘可能減少資源的佔用,取值越小越好
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
//用於進行SocketChannel的網絡讀寫
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//是Netty用於啓動NIO服務端的輔助啓動類,目的是降低服務端的開發複雜度
ServerBootstrap b = new ServerBootstrap();
//配置NIO服務端
b.group(bossGroup, workerGroup)
//指定使用NioServerSocketChannel產生一個Channel用來接收連接,他的功能對應於JDK
// NIO類庫中的ServerSocketChannel類。
.channel(NioServerSocketChannel.class)
//BACKLOG用於構造服務端套接字ServerSocket對象,標識當服務器請求處理線程全滿時,
// 用於臨時存放已完成三次握手的請求的隊列的最大長度。如果未設置或所設置的值小於1,
// Java將使用默認值50。
.option(ChannelOption.SO_BACKLOG, 1024)
//綁定I/O事件處理類,作用類似於Reactor模式中的Handler類,主要用於處理網絡I/O事件
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel arg0) throws Exception {
arg0.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2));
arg0.pipeline().addLast("decoder", new MsgpackDecoder());
arg0.pipeline().addLast("frameEncoder", new LengthFieldPrepender(2));
arg0.pipeline().addLast("encoder", new MsgpackEncoder());
arg0.pipeline().addLast(new ServerHandler());
}
});
//綁定端口,同步等待綁定操作完成,完成後返回一個ChannelFuture,用於異步操作的通知回調
ChannelFuture f = b.bind(port).sync();
//等待服務端監聽端口關閉之後才退出main函數
f.channel().closeFuture().sync();
} finally {
//退出,釋放線程池資源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
/**
* ChannelInboundHandlerAdapter實現自ChannelInboundHandler
* ChannelInboundHandler提供了不同的事件處理方法你可以重寫
*/
class ServerHandler extends ChannelInboundHandlerAdapter {
/**
* 接受客戶端發送的消息
* @param ctx
* @param msg
* @throws Exception
*/
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("Server receive: " + msg);
ctx.write(msg);
}
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//將消息發送隊列中的消息寫入到SocketChannel中發送給對方
ctx.flush();
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
//當發生異常時釋放資源
ctx.close();
}
}
Netty客戶端
package com.ph.Netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
/**
* Create by PH on 2018/11/7
*/
public class NettyClient {
public static void main(String[] args) throws Exception {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
//採用默認值
}
}
new NettyClient().connect(port, "127.0.0.1", 100);
}
public void connect(int port, String host, int sendNumber) throws Exception{
//配置客戶端NIO線程組
EventLoopGroup group = new NioEventLoopGroup();
try{
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
public void initChannel(SocketChannel ch) throws Exception{
ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2));
ch.pipeline().addLast("decoder", new MsgpackDecoder());
ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(2));
ch.pipeline().addLast("encoder", new MsgpackEncoder());
ch.pipeline().addLast(new ClientHandler(sendNumber));
}
});
//發起異步連接操作
ChannelFuture f = b.connect(host, port).sync();
//等待客戶端鏈路關閉
f.channel().closeFuture().sync();
}finally {
group.shutdownGracefully();
}
}
}
class ClientHandler extends ChannelInboundHandlerAdapter {
private int sendNumber;
public ClientHandler(int sendNumber) {
this.sendNumber = sendNumber;
}
/**
* 當客戶端和服務端TCP鏈路建立成功之後,Netty的NIO線程會調用此方法
* @param ctx
*/
public void channelActive(ChannelHandlerContext ctx) {
UserInfo userInfo = null;
for (int i=0;i<sendNumber;i++) {
userInfo = new UserInfo();
userInfo.setAge(i);
userInfo.setName("NAME: " + i);
ctx.write(userInfo);
}
ctx.flush();
}
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
System.out.println("Client receive :" + msg);
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
}
}