EsbNettyService.java 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. package com.nokia.esb_socket.service;
  2. import java.nio.charset.StandardCharsets;
  3. import java.util.concurrent.CompletableFuture;
  4. import java.util.concurrent.ExecutionException;
  5. import javax.annotation.PreDestroy;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.stereotype.Service;
  9. import com.fasterxml.jackson.core.JsonProcessingException;
  10. import com.fasterxml.jackson.databind.ObjectMapper;
  11. import com.nokia.esb_socket.pojo.TousuSheet;
  12. import com.nokia.esb_socket.service.handler.AuthHandler;
  13. import com.nokia.esb_socket.service.handler.HeartbeatHandler;
  14. import com.nokia.esb_socket.service.handler.MessagePrintHandler;
  15. import io.netty.bootstrap.Bootstrap;
  16. import io.netty.channel.Channel;
  17. import io.netty.channel.ChannelFuture;
  18. import io.netty.channel.ChannelInitializer;
  19. import io.netty.channel.ChannelOption;
  20. import io.netty.channel.EventLoopGroup;
  21. import io.netty.channel.nio.NioEventLoopGroup;
  22. import io.netty.channel.socket.SocketChannel;
  23. import io.netty.channel.socket.nio.NioSocketChannel;
  24. import io.netty.handler.codec.string.StringDecoder;
  25. import io.netty.handler.codec.string.StringEncoder;
  26. import io.netty.handler.timeout.IdleStateHandler;
  27. import lombok.extern.slf4j.Slf4j;
  28. /**
  29. * 投诉驱动建设socket接口
  30. */
  31. @Slf4j
  32. @Service
  33. public class EsbNettyService {
  34. @Value("${toususheet.host}")
  35. private String host;
  36. @Value("${toususheet.port}")
  37. private int port;
  38. @Value("${toususheet.userName}")
  39. private String userName;
  40. @Value("${toususheet.password}")
  41. private String password;
  42. private final ObjectMapper objectMapper;
  43. private final EventLoopGroup group;
  44. private Channel channel = null;
  45. @Autowired
  46. public EsbNettyService(ObjectMapper objectMapper) {
  47. this.objectMapper = objectMapper;
  48. // 线程资源在实例初始化时建立
  49. group = new NioEventLoopGroup(1);
  50. }
  51. /**
  52. * 发送消息
  53. *
  54. * @param tousuSheet
  55. */
  56. public void send(TousuSheet tousuSheet) {
  57. if (channel == null || !channel.isActive()) {
  58. // 连接异常
  59. log.info("准备连接到服务器...");
  60. connect();
  61. }
  62. try {
  63. String msg = objectMapper.writeValueAsString(tousuSheet);
  64. synchronized (channel) {
  65. channel.writeAndFlush("<AlarmStart>\r\n" + msg + "\r\n<AlarmEnd>\r\n");
  66. }
  67. } catch (JsonProcessingException e) {
  68. e.printStackTrace();
  69. log.error("发送失败--{}", e.getMessage());
  70. }
  71. }
  72. /**
  73. * 建立连接
  74. */
  75. synchronized public void connect() {
  76. CompletableFuture<Boolean> future = new CompletableFuture<>();
  77. Bootstrap bootstrap = new Bootstrap();
  78. bootstrap.group(group)
  79. .channel(NioSocketChannel.class)
  80. .option(ChannelOption.SO_KEEPALIVE, true)
  81. .handler(new ChannelInitializer<SocketChannel>() {
  82. @Override
  83. protected void initChannel(SocketChannel socketChannel) throws Exception {
  84. socketChannel.pipeline()
  85. .addLast(new StringEncoder(StandardCharsets.UTF_8))
  86. .addLast(new IdleStateHandler(0, 60, 0))
  87. .addLast(new HeartbeatHandler())
  88. .addLast(new StringDecoder(StandardCharsets.UTF_8))
  89. .addLast(new MessagePrintHandler())
  90. .addLast(new AuthHandler(userName, password, future));
  91. }
  92. });
  93. try {
  94. ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
  95. // 建立
  96. channel = channelFuture.channel();
  97. Boolean flag = future.get();
  98. if (flag) {
  99. log.info("通道已激活, 鉴权已通过...");
  100. } else {
  101. disconnect();
  102. throw new RuntimeException("鉴权失败,已断开连接...");
  103. }
  104. } catch (InterruptedException | ExecutionException e) {
  105. e.printStackTrace();
  106. }
  107. }
  108. /**
  109. * 释放连接
  110. */
  111. synchronized public void disconnect() {
  112. if (channel != null) {
  113. try {
  114. channel.closeFuture().sync();
  115. } catch (InterruptedException e) {
  116. e.printStackTrace();
  117. }
  118. channel = null;
  119. }
  120. }
  121. /**
  122. * 由spring框架控制自动释放资源
  123. *
  124. * @throws InterruptedException
  125. */
  126. @PreDestroy
  127. public void tearDown() throws InterruptedException {
  128. group.shutdownGracefully().sync();
  129. }
  130. }