netty

netty是一个nio客户端服务器框架:

  • 它可快速轻松地开发网络应用程序,例如协议服务器和客户端。
  • 它极大地简化和简化了网络编程,例如tcp和udp套接字服务器。

nio是一种非阻塞io ,它具有以下的特点

  • 单线程可以连接多个客户端。
  • 选择器可以实现单线程管理多个channel,新建的通道都要向选择器注册。
  • 一个selectionkey键表示了一个特定的通道对象和一个特定的选择器对象之间的注册关系。
  • selector进行select()操作可能会产生阻塞,但是可以设置阻塞时间,并且可以用wakeup()唤醒selector,所以nio是非阻塞io。

netty模型selector模式

它相对普通nio的在性能上有了提升,采用了:

  • nio采用多线程的方式可以同时使用多个selector
  • 通过绑定多个端口的方式,使得一个selector可以同时注册多个serversocketserver
  • 单个线程下只能有一个selector,用来实现channel的匹配及复用

半包问题

tcp/ip在发送消息的时候,可能会拆包,这就导致接收端无法知道什么时候收到的数据是一个完整的数据。在传统的bio中在读取不到数据时会发生阻塞,但是nio不会。为了解决nio的半包问题,netty在selector模型的基础上,提出了reactor模式,从而解决客户端请求在服务端不完整的问题。

netty模型reactor模式

在selector的基础上解决了半包问题。

上图,简单地可以描述为”boss接活,让work干”:manreactor用来接收请求(会与客户端进行握手验证),而subreactor用来处理请求(不与客户端直接连接)。

springboot使用netty实现远程调用

maven依赖

<!--lombok-->
<dependency>
  <groupid>org.projectlombok</groupid>
  <artifactid>lombok</artifactid>
  <version>1.18.2</version>
  <optional>true</optional>
</dependency>

<!--netty-->
<dependency>
  <groupid>io.netty</groupid>
  <artifactid>netty-all</artifactid>
  <version>4.1.17.final</version>
</dependency>

服务端部分

nettyserver.java:服务启动监听器

@slf4j
public class nettyserver {
    public void start() {
        inetsocketaddress socketaddress = new inetsocketaddress("127.0.0.1", 8082);
        //new 一个主线程组
        eventloopgroup bossgroup = new nioeventloopgroup(1);
        //new 一个工作线程组
        eventloopgroup workgroup = new nioeventloopgroup(200);
        serverbootstrap bootstrap = new serverbootstrap()
                .group(bossgroup, workgroup)
                .channel(nioserversocketchannel.class)
                .childhandler(new serverchannelinitializer())
                .localaddress(socketaddress)
                //设置队列大小
                .option(channeloption.so_backlog, 1024)
                // 两小时内没有数据的通信时,tcp会自动发送一个活动探测数据报文
                .childoption(channeloption.so_keepalive, true);
        //绑定端口,开始接收进来的连接
        try {
            channelfuture future = bootstrap.bind(socketaddress).sync();
            log.info("服务器启动开始监听端口: {}", socketaddress.getport());
            future.channel().closefuture().sync();
        } catch (interruptedexception e) {
            log.error("服务器开启失败", e);
        } finally {
            //关闭主线程组
            bossgroup.shutdowngracefully();
            //关闭工作线程组
            workgroup.shutdowngracefully();
        }
    }
}

serverchannelinitializer.java:netty服务初始化器

/**
* netty服务初始化器
**/
public class serverchannelinitializer extends channelinitializer<socketchannel> {
    @override
    protected void initchannel(socketchannel socketchannel) throws exception {
        //添加编解码
        socketchannel.pipeline().addlast("decoder", new stringdecoder(charsetutil.utf_8));
        socketchannel.pipeline().addlast("encoder", new stringencoder(charsetutil.utf_8));
        socketchannel.pipeline().addlast(new nettyserverhandler());
    }
}

nettyserverhandler.java:netty服务端处理器

/**
* netty服务端处理器
**/
@slf4j
public class nettyserverhandler extends channelinboundhandleradapter {
    /**
     * 客户端连接会触发
     */
    @override
    public void channelactive(channelhandlercontext ctx) throws exception {
        log.info("channel active......");
    }

    /**
     * 客户端发消息会触发
     */
    @override
    public void channelread(channelhandlercontext ctx, object msg) throws exception {
        log.info("服务器收到消息: {}", msg.tostring());
        ctx.write("你也好哦");
        ctx.flush();
    }

    /**
     * 发生异常触发
     */
    @override
    public void exceptioncaught(channelhandlercontext ctx, throwable cause) throws exception {
        cause.printstacktrace();
        ctx.close();
    }
}

rpcserverapp.java:springboot启动类

/**
* 启动类
*
*/
@slf4j
@springbootapplication(exclude = {datasourceautoconfiguration.class})
public class rpcserverapp extends springbootservletinitializer {
    @override
    protected springapplicationbuilder configure(springapplicationbuilder application) {
        return application.sources(rpcserverapp.class);
    }

    /**
     * 项目的启动方法
     *
     * @param args
     */
    public static void main(string[] args) {
        springapplication.run(rpcserverapp.class, args);
        //开启netty服务
        nettyserver nettyserver =new  nettyserver ();
        nettyserver.start();
        log.info("======服务已经启动========");
    }
}

客户端部分

nettyclientutil.java:nettyclient工具类

/**
* netty客户端
**/
@slf4j
public class nettyclientutil {

    public static responseresult hellonetty(string msg) {
        nettyclienthandler nettyclienthandler = new nettyclienthandler();
        eventloopgroup group = new nioeventloopgroup();
        bootstrap bootstrap = new bootstrap()
                .group(group)
                //该参数的作用就是禁止使用nagle算法,使用于小数据即时传输
                .option(channeloption.tcp_nodelay, true)
                .channel(niosocketchannel.class)
                .handler(new channelinitializer<socketchannel>() {
                    @override
                    protected void initchannel(socketchannel socketchannel) throws exception {
                        socketchannel.pipeline().addlast("decoder", new stringdecoder());
                        socketchannel.pipeline().addlast("encoder", new stringencoder());
                        socketchannel.pipeline().addlast(nettyclienthandler);
                    }
                });
        try {
            channelfuture future = bootstrap.connect("127.0.0.1", 8082).sync();
            log.info("客户端发送成功....");
            //发送消息
            future.channel().writeandflush(msg);
            // 等待连接被关闭
            future.channel().closefuture().sync();
            return nettyclienthandler.getresponseresult();
        } catch (exception e) {
            log.error("客户端netty失败", e);
            throw new businessexception(coupontypeenum.operate_error);
        } finally {
            //以一种优雅的方式进行线程退出
            group.shutdowngracefully();
        }
    }
}

nettyclienthandler.java:客户端处理器

/**
* 客户端处理器
**/
@slf4j
@setter
@getter
public class nettyclienthandler extends channelinboundhandleradapter {

    private responseresult responseresult;

    @override
    public void channelactive(channelhandlercontext ctx) throws exception {
        log.info("客户端active .....");
    }

    @override
    public void channelread(channelhandlercontext ctx, object msg) throws exception {
        log.info("客户端收到消息: {}", msg.tostring());
        this.responseresult = responseresult.success(msg.tostring(), coupontypeenum.operate_success.getcoupontypedesc());
        ctx.close();
    }

    @override
    public void exceptioncaught(channelhandlercontext ctx, throwable cause) throws exception {
        cause.printstacktrace();
        ctx.close();
    }
}

验证

测试接口

@restcontroller
@slf4j
public class usercontroller {

    @postmapping("/hellonetty")
    @methodlogprint
    public responseresult hellonetty(@requestparam string msg) {
        return nettyclientutil.hellonetty(msg);
    }
}

访问测试接口

服务端打印信息

客户端打印信息

到此这篇关于在springboot中,如何使用netty实现远程调用方法总结的文章就介绍到这了,更多相关netty实现远程调用内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!