AcceptanceService.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package com.tidecloud.dataacceptance.service;
  2. import java.util.concurrent.TimeUnit;
  3. import javax.annotation.PostConstruct;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.stereotype.Component;
  7. import com.tidecloud.dataacceptance.service.impl.WatchServerHandler;
  8. import io.netty.bootstrap.ServerBootstrap;
  9. import io.netty.channel.ChannelFuture;
  10. import io.netty.channel.ChannelInitializer;
  11. import io.netty.channel.ChannelOption;
  12. import io.netty.channel.EventLoopGroup;
  13. import io.netty.channel.nio.NioEventLoopGroup;
  14. import io.netty.channel.socket.SocketChannel;
  15. import io.netty.channel.socket.nio.NioServerSocketChannel;
  16. import io.netty.handler.timeout.IdleStateHandler;
  17. /**
  18. * Hello world!
  19. */
  20. @Component
  21. public class AcceptanceService {
  22. @Value("${server.netty.port}")
  23. private Integer port;
  24. @Autowired
  25. private WatchServerHandler watchServcie;
  26. @PostConstruct
  27. public void run() throws Exception {
  28. new Thread(new Runnable() {
  29. @Override
  30. public void run() {
  31. EventLoopGroup bossGroup = new NioEventLoopGroup();
  32. EventLoopGroup workerGroup = new NioEventLoopGroup();
  33. try {
  34. ServerBootstrap b = new ServerBootstrap();
  35. b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).
  36. childHandler(new ChannelInitializer<SocketChannel>() {
  37. @Override
  38. protected void initChannel(SocketChannel ch) throws Exception {
  39. ch.pipeline().addLast("idleStateHandler",
  40. new IdleStateHandler(10, 0, 0, TimeUnit.MINUTES));
  41. ch.pipeline().addLast(watchServcie);
  42. }
  43. })
  44. .option(ChannelOption.SO_BACKLOG, 128)
  45. .childOption(ChannelOption.SO_KEEPALIVE, true);
  46. ChannelFuture f = b.bind(port).sync();
  47. f.channel().closeFuture().sync();
  48. } catch (InterruptedException e) {
  49. e.printStackTrace();
  50. } finally {
  51. workerGroup.shutdownGracefully();
  52. bossGroup.shutdownGracefully();
  53. }
  54. }
  55. }).start();
  56. }
  57. }