Netty是由JBOSS提供的一个开源的java网络编程框架,主要是对java的nio包进行了再次封装。
1: 启动类,已经整合了spring boot 当启动项目时候同时启动netty 的端口服务
(弊端就是启动了俩个端口: 一个是spring boot 的端口,一个是netty的端口
由于没有特殊要求所以没去处理这个问题,解决了或者有解决办法的小伙伴可以回复下
好让我吸取吸取意见)。
可以清楚的看到这些包在maven 中都能找到,如果有没贴出来的class ,请回复!
package cn.unicom.iot.gather.levle.server;
import cn.unicom.iot.gather.levle.server.netty.NettyServer;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@SpringBootApplication
@EnableAspectJAutoProxy
@EnableCircuitBreaker
public class Application implements CommandLineRunner {
@Autowired(required = false)
private NettyServer server;
private static final Logger logger = Logger.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
server.start();
}
}
2:接下来是 netty 服务类
简单解释下这个netty服务类:抽象decode方法 ,任何的数据协议,只要是称得上是协议,就会有固定的格式
在我们知道了格式后,就需要到了解码器 就是decode。
Handle 接受到了再decode 接受数据处理之后的集合,进行业务处理。
package cn.unicom.iot.gather.levle.server.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
/**
* 主要思路:
* 实现了一个解码器SunseaMessageDecoder和一个业务处理的SunseaMessageHandler
* 客户端发送报文协议
* 服务器端接收后解析数据,进行业务逻辑处理
* 在这过程中可以看到解码器的作用
*/
public class NettyServer {
@Autowired
private SunseaMessageHandler serverMessageHandler;
private static final Logger logger = Logger.getLogger(NettyServer.class);