netty(二)–使用Marshalling编解码java对象
文章目录
一、简介
marshalling是jboss的java对象序列化包,修正了jdk原生序列化存在的问题,保持了对java.io.Serializable接口的兼容,这里介绍以marshalling为编解码工具在netty中的使用。
二、代码示例
2.1 添加maven依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>5.0.0.Alpha2</version>
</dependency>
<dependency>
<groupId>org.jboss.marshalling</groupId>
<artifactId>jboss-marshalling-serial</artifactId>
<version>2.0.6.Final</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
2.2 定义消息对象
package com.dragon.study.netty;
import lombok.Data;
import java.io.Serializable;
@Data
public class Msg implements Serializable {
private String id;
private String content;
public Msg(String id, String content) {
this.id = id;
this.content = content;
}
}
2.3 定义marshalling编解码工具
package com.dragon.study.netty;
import io.netty.handler.codec.marshalling.*;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;
public class MarshallingFactory {
//生成Marshalling工厂类
private static MarshallerFactory mf = Marshalling.getProvidedMarshallerFactory("serial");
private static MarshallingConfiguration conf = new MarshallingConfiguration