Netty(二)之整合Marshalling传输实体类

简介: Netty(二)之整合Marshalling传输实体类

pom


        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>5.0.0.Alpha1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jboss.marshalling/jboss-marshalling-serial -->
        <dependency>
            <groupId>org.jboss.marshalling</groupId>
            <artifactId>jboss-marshalling-serial</artifactId>
            <version>1.3.14.GA</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jboss.marshalling/jboss-marshalling-river -->
        <dependency>
            <groupId>org.jboss.marshalling</groupId>
            <artifactId>jboss-marshalling-river</artifactId>
            <version>2.0.5.Final</version>
        </dependency>


自定义实体类


使用lombok添加的get、set、无参构造方法


package jbossmarshalling;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
 * @author CBeann
 * @create 2019-08-31 11:05
 */
@Data
public class Book implements Serializable {
    private Integer id;
    private String name;
    private Date date;
}


MarshallingCodeCFactory编解码工具类


固定格式,类似工具类


package jbossmarshalling;
import io.netty.handler.codec.marshalling.*;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;
/**
 * @author CBeann
 * @create 2019-08-31 14:36
 */
public final class MarshallingCodeCFactory {
    //创建JBoss Marshalling解码器MarshallingDecoder
    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;
    }
    //创建JBoss Marshalling编码器MarshallingEncoder
    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;
    }
}


TimeServerHandler


package jbossmarshalling;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
 * @author CBeann
 * @create 2019-08-27 18:31
 */
public class TimeServerHandler extends ChannelHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //服务器读客户端发送来的数据
        Book body = (Book) msg;
        System.out.println("The TimeServer receive :" + body);
        //服务器向客户端回应请求
        Book response = new Book();
        response.setId(11);
        response.setName("hello");
        ctx.writeAndFlush(response);
    }
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //将消息发送队列中的消息写入到SocketChannel中发送给对方
        ctx.flush();
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}


TimeServer


package jbossmarshalling;
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;
/**
 * @author CBeann
 * @create 2019-08-27 18:22
 */
public class TimeServer {
    public static void main(String[] args) throws Exception {
        int port = 8080;
        //配置服务器端的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>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //重点
                            socketChannel.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                            socketChannel.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                            socketChannel.pipeline().addLast(new TimeServerHandler());
                        }
                    });
            //绑定端口
            ChannelFuture f = b.bind(port).sync();
            //等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        } catch (Exception e) {
        } finally {
            //优雅关闭,释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}


TimeClientHandler


package jbossmarshalling;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
/**
 * @author CBeann
 * @create 2019-08-27 18:47
 */
public class TimeClientHandler extends ChannelHandlerAdapter {
    //客户端读取服务器发送的数据
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            Book body = (Book) msg;
            System.out.println("Now is:" + body);
        } catch (Exception e) {
        } finally {
            //标配
            ReferenceCountUtil.release(msg);
        }
    }
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //将消息发送队列中的消息写入到SocketChannel中发送给对方
        ctx.flush();
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}


TimeClient


package jbossmarshalling;
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;
import java.util.Date;
/**
 * @author CBeann
 * @create 2019-08-27 18:43
 */
public class TimeClient {
    public static void main(String[] args) throws Exception {
        int port = 8080;
        String host = "127.0.0.1";
        //配置客户端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>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
                            socketChannel.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
                            socketChannel.pipeline().addLast(new TimeClientHandler());
                        }
                    });
            //发起异步连接操作
            ChannelFuture f = b.connect(host, port).sync();
            Book book = new Book();
            book.setId(1);
            book.setName("十万个为什么");
            book.setDate(new Date());
            //f.channel().writeAndFlush(Unpooled.copiedBuffer("您好".getBytes()));
            f.channel().writeAndFlush(book);
            //Thread.sleep0);//防止TCP粘包
            //等待客户端链路关闭
            f.channel().closeFuture().sync();
        } catch (Exception e) {
        } finally {
            //优雅关闭
            group.shutdownGracefully();
        }
    }
}


出现的问题


1)代码没有问题,就是客户端服务器端不交互


依赖有问题


 <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>5.0.0.Alpha1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jboss.marshalling/jboss-marshalling-serial -->
        <dependency>
            <groupId>org.jboss.marshalling</groupId>
            <artifactId>jboss-marshalling-serial</artifactId>
            <version>1.3.14.GA</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jboss.marshalling/jboss-marshalling-river -->
        <dependency>
            <groupId>org.jboss.marshalling</groupId>
            <artifactId>jboss-marshalling-river</artifactId>
            <version>2.0.5.Final</version>
        </dependency>


结果


亲测有效

目录
相关文章
|
5月前
|
Java
Netty传输object并解决粘包拆包问题
Netty传输object并解决粘包拆包问题
49 0
|
网络协议 前端开发 Linux
快来体验快速通道,netty中epoll传输协议详解
在前面的章节中,我们讲解了kqueue的使用和原理,接下来我们再看一下epoll的使用。两者都是更加高级的IO方式,都需要借助native的方法实现,不同的是Kqueue用在mac系统中,而epoll用在liunx系统中。
|
存储 Java Linux
Netty实战(四)Netty的传输
流经网络的数据总是具有相同的类型:字节。这些字节是如何流动的主要取决于我们所说的网络传输。
182 0
|
编解码 安全 前端开发
在netty中使用protobuf并实现数据加密传输
在netty中使用protobuf并实现数据加密传输
526 0
在netty中使用protobuf并实现数据加密传输
|
Java 应用服务中间件 程序员
netty系列之:使用Jboss Marshalling来序列化java对象
在JAVA程序中经常会用到序列化的场景,除了JDK自身提供的Serializable之外,还有一些第三方的产品可以实现对JAVA对象的序列化。其中比较有名的就是Google protobuf。当然,也有其他的比较出名的序列化工具,比如Kryo和JBoss Marshalling。
|
存储 安全 Java
【Netty】Netty传输
在简单学习了Netty中的组件后,接着学习Netty中数据的传输细节。
158 0
【Netty】Netty传输
|
网络协议
netty系列之:kequeue传输协议详解
在前面的章节中,我们介绍了在netty中可以使用kequeue或者epoll来实现更为高效的native传输方式。那么kequeue和epoll和NIO传输协议有什么不同呢? 本章将会以kequeue为例进行深入探讨。
|
前端开发 Ubuntu Java
netty系列之:在netty中使用native传输协议
对于IO来说,除了传统的block IO,使用最多的就是NIO了,通常我们在netty程序中最常用到的就是NIO,比如NioEventLoopGroup,NioServerSocketChannel等。
|
设计模式 JSON Java
RPC框架(3 - 实现Netty传输和通用序列化接口)
RPC框架(3 - 实现Netty传输和通用序列化接口)
|
存储 Java 应用服务中间件
netty系列之:netty对marshalling的支持
在之前的文章中我们讲过了,jboss marshalling是一种非常优秀的java对象序列化的方式,它可以兼容JDK自带的序列化,同时也提供了性能和使用上的优化。 那么这么优秀的序列化工具可不可以用在netty中作为消息传递的方式呢? 答案当然是肯定的,在netty中一切皆有可能。