1、MessagePack API 介绍
package com.suirui.messagepack.entity;
public class Person {
private String name;
private int age;
private boolean sex;
public Person(){}
public Person(String name, int age, boolean sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Person[name = " + name + ",age = " + age + ",sex = " + sex + "]";
}
}
package com.suirui.messagepack;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.suirui.messagepack.entity.Person;
import com.suirui.messagepack.util.MsgPackUtil;
import org.msgpack.jackson.dataformat.MessagePackFactory;
import javax.xml.transform.Templates;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* Created by zongx on 2019/12/27.
*/
public class MsgPackTest {
private ObjectMapper mapper;
public MsgPackTest() {
mapper = new ObjectMapper(new MessagePackFactory());
}
public static void main(String[] args) throws IOException {
ArrayList<String> list = new ArrayList<>();
list.add("msgpack");
list.add("kumofs");
list.add("viver");
MsgPackTest msgPackTest = new MsgPackTest();
// msgPackTest.serialObject();
// msgPackTest.serialList();
msgPackTest.utilTestObject();
// msgPackTest.utilTestList();
}
public void serialObject() throws IOException {
Person jemmy = new Person("jemmy", 18, true);
//序列化
byte[] bytes = mapper.writeValueAsBytes(jemmy);
//序列化之后数组长度
System.out.println(bytes.length);
System.out.println(Arrays.toString(bytes));
//反序列化
Person person = mapper.readValue(bytes, Person.class);
System.out.println(person);
}
public void serialList() throws IOException {
LinkedList<Person> people = new LinkedList<>();
Person rose = new Person("rose", 18, false);
Person jack = new Person("jack", 18, true);
people.add(rose);
people.add(jack);
//序列化
byte[] bytes = mapper.writeValueAsBytes(people);
//序列化之后数组长度
System.out.println(bytes.length);
System.out.println(Arrays.toString(bytes));
//反序列化
JavaType type = mapper.getTypeFactory().constructParametricType(ArrayList.class, Person.class);
ArrayList<Person> list = mapper.readValue(bytes, type);
System.out.println(list);
}
public void utilTestObject() throws IOException {
Person jemmy = new Person("jemmy", 18, true);
//序列化
byte[] bytes = MsgPackUtil.serializeObject(jemmy);
//序列化之后数组长度
System.out.println(bytes.length);
System.out.println(Arrays.toString(bytes));
//反序列化
Person person = MsgPackUtil.deserializeObject(bytes, Person.class);
System.out.println(person);
}
public void utilTestList() throws IOException {
LinkedList<Person> people = new LinkedList<>();
Person rose = new Person("rose", 18, false);
Person jack = new Person("jack", 18, true);
people.add(rose);
people.add(jack);
//序列化
byte[] bytes = MsgPackUtil.serializeObject(people);
//序列化之后数组长度
System.out.println(bytes.length);
System.out.println(Arrays.toString(bytes));
//反序列化
List<Person> list = MsgPackUtil.deserializeList(bytes,Person.class);
System.out.println(list);
}
}
package com.suirui.messagepack.util;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.msgpack.jackson.dataformat.MessagePackFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by zongx on 2019/12/27.
*/
public class MsgPackUtil {
private static ObjectMapper mapper = new ObjectMapper(new MessagePackFactory());
/**
* @Description: 对象序列化
* @Author: zongx
* @Date: 2019/12/27
* @Param: t
* @return byte[]
*/
public static<T> byte[] serializeObject(T t) throws IOException {
return mapper.writeValueAsBytes(t);
}
/**
* 泛型方法的基本介绍
* 说明:
* 1)public 与 返回值中间<T>非常重要,可以理解为声明此方法为泛型方法。
* 2)只有声明了<T>的方法才是泛型方法,泛型类中的使用了泛型的成员方法并不是泛型方法。
* 3)<T>表明该方法将使用泛型类型T,此时才可以在方法中使用泛型类型T。
* 4)与泛型类的定义一样,此处T可以随便写为任意标识,常见的如T、E、K、V等形式的参数常用于表示泛型。
*/
public static <T> T deserializeObject(byte[] bytes,Class<T> clazz) throws IOException {
return mapper.readValue(bytes,clazz);
}
/**
* @Description: 根据传参返回反序列化List
* @Author: zongx
* @Date: 2019/12/27
* @Param: bytes
* @Param: clazz
* @return java.util.List<T>
*/
public static <T> List<T> deserializeList(byte[] bytes,Class<T> clazz) throws IOException {
JavaType type = getListJavaType(clazz);
return mapper.readValue(bytes,type);
}
/**
* @Description: 获取List的javatype
* @Author: zongx
* @Date: 2019/12/27
* @Param: clazz
* @return com.fasterxml.jackson.databind.JavaType
*/
private static <T> JavaType getListJavaType(Class<T> clazz) {
return mapper.getTypeFactory().constructParametricType(ArrayList.class,clazz);
}
}
2、使用MessagePack实现netty EchoServer
decode
package com.suirui.messagepack.decoder;
import com.suirui.messagepack.util.MsgPackUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import java.util.List;
/**
* Created by zongx on 2019/12/27.
*/
public class MsgPackDecoder extends MessageToMessageDecoder<ByteBuf> {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
byte[] bytes = new byte[msg.readableBytes()];
msg.readBytes(bytes);
out.add(MsgPackUtil.deserializeObject(bytes, Object.class));
}
}
encode
package com.suirui.messagepack.encoder;
import com.suirui.messagepack.util.MsgPackUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.MessageToMessageEncoder;
import java.util.List;
/**
* Created by zongx on 2019/12/27.
*/
public class MsgPackEncoder extends MessageToByteEncoder<Object> {
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
byte[] bytes = MsgPackUtil.serializeObject(msg);
out.writeBytes(bytes);
}
}
EchoServer
package com.suirui.messagepack.server;
import com.suirui.messagepack.decoder.MsgPackDecoder;
import com.suirui.messagepack.encoder.MsgPackEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
/**
* Created by zongx on 2019/12/27.
*/
public class EchoServer {
private int port;
public EchoServer(int port) {
this.port = port;
}
public static void main(String[] args) {
int port = 8080;
if (args != null && args.length > 1) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
new EchoServer(port).run();
}
public void run() {
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup,workGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.childHandler(new ChannelInitializerHandler());
System.out.println("echoServer 启动端口 " + port);
try {
ChannelFuture sync = b.bind(port).sync();
sync.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class ChannelInitializerHandler extends ChannelInitializer {
@Override
protected void initChannel(Channel ch) throws Exception {
//首先加入LengthFieldBasedFrameDecoder解码器,解决tcp粘包和拆包的问题
ch.pipeline().addLast("frameDecoder",new LengthFieldBasedFrameDecoder(65535, 0,2,0,2));
//加入MessagePackDcoder
ch.pipeline().addLast("msgPack decoder", new MsgPackDecoder());
//加入LengthFieldPrepender编码器,解决tcp粘包和拆包的问题
ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(2));
//加入MessagePackEncoder
ch.pipeline().addLast("msgPack encoder", new MsgPackEncoder());
//业务逻辑
ch.pipeline().addLast(new EchoServerHandler());
}
}
}
package com.suirui.messagepack.server;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
private int count = 0 ;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//由于MessagePack编解码器的存在,到此处的msg,已经是Person对象,可以强转成Persion对象
System.out.println("Server收到的消息:" + msg + "当前次数: " +count++);
ctx.writeAndFlush(msg); //收到消息后直接返回给Client
}
/**
* 异常的时候打印栈和关闭channel上下文对象
* @param ctx
* @param cause
* @throws Exception
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
echoclient
package com.suirui.messagepack.client;
import com.suirui.messagepack.decoder.MsgPackDecoder;
import com.suirui.messagepack.encoder.MsgPackEncoder;
import com.suirui.messagepack.server.EchoServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import java.net.InetSocketAddress;
/**
* Created by zongx on 2019/12/27.
*/
public class EchoClient {
private int port;
private String host;
public EchoClient(int port,String host) {
this.port = port;
this.host = host;
}
public static void main(String[] args) {
int port = 8080;
String host = "127.0.0.1";
new EchoClient(port,host).run();
}
public void run() {
NioEventLoopGroup workGroup = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(workGroup)
.channel(NioSocketChannel.class)
.remoteAddress(new InetSocketAddress(host, port))
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
.handler(new ChannelInitializerHandler());
System.out.println("echoServer 启动端口 " + port);
try {
ChannelFuture future = b.connect().sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class ChannelInitializerHandler extends ChannelInitializer {
@Override
protected void initChannel(Channel ch) throws Exception {
//首先加入LengthFieldBasedFrameDecoder解码器,解决tcp粘包和拆包的问题
ch.pipeline().addLast("frameDecoder",new LengthFieldBasedFrameDecoder(65535, 0,2,0,2));
//加入MessagePackDcoder
ch.pipeline().addLast("msgPack decoder", new MsgPackDecoder());
//加入LengthFieldPrepender编码器,解决tcp粘包和拆包的问题
ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(2));
//加入MessagePackEncoder
ch.pipeline().addLast("msgPack encoder", new MsgPackEncoder());
//业务逻辑
ch.pipeline().addLast(new EchoClientHandler(10));
}
}
}
package com.suirui.messagepack.client;
import com.suirui.messagepack.entity.Person;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class EchoClientHandler extends ChannelInboundHandlerAdapter {
private int sendNumber;
public EchoClientHandler(int sendNumber){
this.sendNumber = sendNumber;
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//发送对象数据给服务端
Person[] persons = persionInfo();
for (Person p:persons) {
ctx.write(p);
}
ctx.flush();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//打印服务端发送的数据
System.out.println("Client recieve message:" + msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
/**
* 初始化发送的消息对象
* @return
*/
private Person [] persionInfo(){
Person[] persons = new Person[sendNumber];
Person person = null;
for (int i = 0; i < sendNumber ; i++) {
person = new Person("Jemmy===>" + i, 10 + i, true);
persons[i] = person;
}
return persons;
}
}
<dependencies>
<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.32.Final</version>
</dependency>
<dependency>
<groupId>org.msgpack</groupId>
<artifactId>msgpack-core</artifactId>
<version>0.8.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.msgpack/jackson-dataformat-msgpack -->
<dependency>
<groupId>org.msgpack</groupId>
<artifactId>jackson-dataformat-msgpack</artifactId>
<version>0.8.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.35</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.7.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.1</version>
</dependency>
</dependencies>