SpringBoot+Netty+WebSocket 如何实现消息推送

Netty 是一个利用 Java 的高级网络的能力,隐藏底层的复杂性而提供一个易于使用/使用其服务器的 API 的客户端框架。

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://gitee.com/zhijiantianya/ruoyi-vue-pro
  • 视频教程:https://doc.iocoder.cn/video/

Maven依赖


 
 
   io.netty
   netty-all
   4.1.36.Final
 



基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://gitee.com/zhijiantianya/yudao-cloud
  • 视频教程:https://doc.iocoder.cn/video/

启动器中需要new一个NettyServer,并显式调用netty。

@SpringBootApplication
public  class SpringCloudStudyDemoApplication {
  public static void main(String[] args) {
  SpringApplication.run(SpringCloudStudyDemoApplication .class,args);
   try {
    new NettyServer( 12345).start();
   System.out.println( "https://blog.csdn.net/moshowgame");
   System.out.println( "http://127.0.0.1:6688/netty-websocket/index");
  } catch(Exception e) {
   System.out.println( "NettyServerError:"+e.getMessage());
  }
 }
}

网络服务器

启动的NettyServer,这里进行配置

/**
 * NettyServer Netty服务器配置
 * @author zhengkai.blog.csdn.net
 * @date 2019-06-12
 */

public  class NettyServer {
     private  final  int port;
 
     public NettyServer(int port) {
         this.port = port;
    }
 
     public void start() throws Exception {
        EventLoopGroup bossGroup =  new NioEventLoopGroup();
 
        EventLoopGroup group =  new NioEventLoopGroup();
         try {
            ServerBootstrap sb =  new ServerBootstrap();
            sb.option(ChannelOption.SO_BACKLOG,  1024);
            sb.group(group, bossGroup)  // 绑定线程池
                    .channel(NioServerSocketChannel .class) // 指定使用的channel
                    .localAddress(this.port)// 绑定监听端口
                    .childHandler(new ChannelInitializer() {  // 绑定客户端连接时候触发操作
 
                         @Override
                         protected void initChannel(SocketChannel ch) throws Exception {
                            System.out.println( "收到新连接");
                             //websocket协议本身是基于http协议的,所以这边也要使用http解编码器
                            ch.pipeline().addLast( new HttpServerCodec());
                             //以块的方式来写的处理器
                            ch.pipeline().addLast( new ChunkedWriteHandler());
         &

你可能感兴趣的:(rxjava,java,java-ee,架构,后端)