这里主要说使用Netty作为服务端的情况,主要思路:
- 把Netty需要的资源封装到一个Server类中
- 基于Spring Bean的生命周期,在Bean创建的时候启动Netty,在Bean销毁的时候关闭Netty
示例:
package com.semonx.netty;
import java.net.InetSocketAddress;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
@Component
public class NewTankServer {
private final static Logger LOGGER = LoggerFactory.getLogger(NewTankServer.class);
private EventLoopGroup parentGroup = new NioEventLoopGroup();
private EventLoopGroup childGroup = new NioEventLoopGroup();
private int port = 7707;
@PostConstruct
public void start() throws InterruptedException {
ServerBootstrap bootstrap = new ServerBootstrap()
.group(parentGroup, childGroup)
.localAddress(new InetSocketAddress(port))
.channel(NioServerSocketChannel.class)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ServerInitializer());
ChannelFuture future = bootstrap.bind().sync();
if (future.isSuccess()) {
LOGGER.info("服务启动成功。监听端口: " + port);
}
}
@PreDestroy
public void destroy() {
parentGroup.shutdownGracefully().syncUninterruptibly();
childGroup.shutdownGracefully().syncUninterruptibly();
LOGGER.info("服务成功停止");
}
}