1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- package cn.com.zyjblogs.chat.netty;
- import io.netty.bootstrap.ServerBootstrap;
- import io.netty.channel.ChannelFuture;
- import io.netty.channel.nio.NioEventLoopGroup;
- import io.netty.channel.socket.nio.NioServerSocketChannel;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Service;
- import javax.annotation.Resource;
- import java.io.Closeable;
- /**
- * @author Gjing
- **/
- @Slf4j
- @Service
- public class SocketServer implements Runnable, Closeable {
- @Resource
- private SocketInitializer socketInitializer;
- /**
- * netty服务监听端口
- */
- @Value("${spring.netty.port:8808}")
- private int port;
- /**
- * 主线程组数量
- */
- @Value("${spring.netty.bossThread:1}")
- private int bossThread;
- private ServerBootstrap serverBootstrap = new ServerBootstrap();
- // 创建两个线程组,bossGroup为接收请求的线程组,一般1-2个就行
- private NioEventLoopGroup bossGroup = new NioEventLoopGroup(this.bossThread);
- // 实际工作的线程组
- private NioEventLoopGroup workerGroup = new NioEventLoopGroup();
- /**
- * 初始化netty配置
- */
- private void init() {
- this.serverBootstrap.group(bossGroup, workerGroup) // 两个线程组加入进来
- .channel(NioServerSocketChannel.class) // 配置为nio类型
- .childHandler(this.socketInitializer); // 加入自己的初始化器
- //对关闭通道进行监听
- ChannelFuture cf = this.serverBootstrap.bind(this.port);
- //对关闭通道进行监听
- try {
- cf.channel().closeFuture().sync();
- } catch (InterruptedException e) {
- }
- }
- /**
- * 启动netty服务器
- */
- @Override
- public void run() {
- init();
- }
- @Override
- public void close() {
- //优雅关闭
- log.info("netty closing");
- bossGroup.shutdownGracefully();
- workerGroup.shutdownGracefully();
- log.info("netty close");
- }
- }
|