Netty学习之路(九)-JBoss Marshalling编解码

本文介绍了如何在Netty中使用JBoss Marshalling进行对象序列化,包括环境准备、编解码器创建、POJO类设计、服务端和客户端的开发,以及运行验证,展示了Marshalling编解码器对半包和粘包的良好支持。
摘要由CSDN通过智能技术生成

JBoss Marshalling 是一个Java对象序列化包,对JDK默认的序列化框架进行了优化,但又保持跟java.io.Serializable接口的兼容,同时增加了一些可调的参数和附加的特性。

Marshalling开发环境准备

下载相关的Marshalling类库:地址,将该jar导入项目即可。

创建Marshalling编解码器

通过创建MarshallingCodeCFactory工厂类来创建MarshallingDecoder解码器与MarshallingEncoder编码器。

package com.ph.Netty;

import io.netty.handler.codec.marshalling.*;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;

/**
 * Create by PH on 2018/11/10
 */
public final class MarshallingCodeCFactory {

    /**
     * JBoss Marshalling 解码器
     * @return
     */
    public static MarshallingDecoder buildMarshallingDecoder() {
        //参数“serial”表示创建的是Java序列化工厂对象
        final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
        final MarshallingConfiguration configuration = new MarshallingConfiguration();
        configuration.setVersion(5);
        UnmarshallerProvider provider = new DefaultUnmarshallerProvider(marshallerFactory, configuration);
        //1024表示单个消息序列化后的最大长度
        MarshallingDecoder decoder = new MarshallingDecoder(provider, 1024);
        return decoder;
    }

    /**
     * JBoss Marshalling 编码器
     * @return
     */
    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(provid
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值