在SpringBoot中启动Netty
方式1
-
设置一个ApplicationListener
@Component public class NettyBooter implements ApplicationListener<ContextRefreshedEvent>{ @Override public void onApplicationEvent(ContextRefreshedEvent event) { if(event.getApplicationContext().getParent()==null) { try { NettyServer.getInstance().start(); } catch (Exception e) { e.printStackTrace(); } } } }
-
NettyServer
@Component public class NettyServer { private static class SingletonNettyServer{ static final NettyServer instance = new NettyServer(); } private EventLoopGroup mainGroup; private EventLoopGroup subGroup; private ServerBootstrap serverBootstrap; private ChannelFuture future; public static NettyServer getInstance() { return SingletonNettyServer.instance; } public NettyServer(){ mainGroup = new NioEventLoopGroup(); subGroup = new NioEventLoopGroup(); serverBootstrap = new ServerBootstrap(); serverBootstrap.group(mainGroup, subGroup) .channel(NioServerSocketChannel.class) .childHandler(new NettyServerInitializer()); } public void start(){ this.future = serverBootstrap.bind(9999); System.err.println("netty 服务启动成功"); } }
方式2
使用注解@PostConstruct启动
@Component大家都能熟悉了,就是把普通pojo实例化到spring容器中,相当于配置文件中的
。泛指各种组件,比如类不属于@Controller或者@Service等时,就可以用该注解标注; @PostConstruct这个注解是我第一次接触,在方法上加该注解会在项目启动的时候执行该方法,即spring容器初始化的时候执行,它与构造函数及@Autowired的执行顺序为:构造函数 >> @Autowired >> @PostConstruct,由此看来当我们想在生成对象时完成某些初始化操作,而偏偏这些初始化操作又依赖于注入的bean,那么就无法在构造函数中实现,为此可以使用@PostConstruct注解一个init方法来完成初始化,该方法会在bean注入完成后被自动调用。
@Component
public class NettyServer {
private EventLoopGroup mainGroup;
private EventLoopGroup subGroup;
private ServerBootstrap serverBootstrap;
private ChannelFuture future;
public NettyServer(){
mainGroup = new NioEventLoopGroup();
subGroup = new NioEventLoopGroup();
serverBootstrap = new ServerBootstrap();
serverBootstrap.group(mainGroup, subGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new NettyServerInitializer());
}
@PostConstruct
public void start(){
this.future = serverBootstrap.bind(9999);
System.err.println("netty 服务启动成功");
}
}