‘liusuyi’
2023-12-28 eae9c75f70004dfe128718c63fe04c1a5cc35b01
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package com.ard.utils.netty.tcp;
 
import com.ard.alarm.radar.domain.ArdEquipRadar;
import com.ard.alarm.radar.service.IArdEquipRadarService;
import com.ard.utils.netty.config.NettyTcpConfiguration;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
 
import javax.annotation.Resource;
import java.nio.channels.SocketChannel;
import java.util.List;
 
@Slf4j(topic = "netty")
@Component
public class BootNettyClient implements ApplicationRunner {
    @Resource
    IArdEquipRadarService ardEquipRadarService;
    @Resource
    NettyTcpConfiguration nettyTcpConfig;
    static Integer waitTimes = 1;
    static EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    /**
     * 初始化Bootstrap
     */
    public static final Bootstrap getBootstrap(EventLoopGroup group) {
        if (null == group) {
            group = eventLoopGroup;
        }
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true).handler(new BootNettyChannelInitializer<SocketChannel>());
        return bootstrap;
    }
 
    public void connect( String host,int port) throws Exception {
        log.debug("正在进行连接:【" + host+":"+port+"】");
        eventLoopGroup.shutdownGracefully();
        eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = getBootstrap(null);
 
        try {
            bootstrap.remoteAddress(host, port);
            // 异步连接tcp服务端
            ChannelFuture future = bootstrap.connect().addListener((ChannelFuture futureListener) -> {
                final EventLoop eventLoop = futureListener.channel().eventLoop();
                if (futureListener.isSuccess()) {
                    BootNettyClientChannel bootNettyClientChannel = new BootNettyClientChannel();
                    Channel channel = futureListener.channel();
                    String id = futureListener.channel().id().toString();
//                    String id = host;
                    bootNettyClientChannel.setChannel(channel);
                    bootNettyClientChannel.setCode("clientId:" + id);
                    BootNettyClientChannelCache.save("clientId:" + id, bootNettyClientChannel);
                    log.debug("netty client start success=" + id);
                } else {
//                    System.err.println("连接失败," + waitTimes.toString() + "秒后重新连接:" + host);
                    try {
                        Thread.sleep(waitTimes * 1000);
                    } finally {
                        connect(host,port);
                    }
                }
            });
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            System.err.println("连接异常," + waitTimes.toString() + "秒后重新连接:" + host);
            try {
                Thread.sleep(waitTimes * 1000);
            } finally {
                connect(host,port);
            }
            e.printStackTrace();
        } finally {
            /**
             * 退出,释放资源
             */
            eventLoopGroup.shutdownGracefully().sync();
        }
 
    }
    /**
     * 初始化方法
     */
    @Override
    public void run(ApplicationArguments args) {
        if (!nettyTcpConfig.getEnabled()) {
            return;
        }
        List<ArdEquipRadar> ardEquipRadars = ardEquipRadarService.selectArdEquipRadarList(new ArdEquipRadar());
        for (ArdEquipRadar ardEquipRadar : ardEquipRadars) {
            String host = ardEquipRadar.getIp();
            Integer port = Integer.valueOf(ardEquipRadar.getPort());
            log.debug("TCP client try to connect radar【:" + host + ":" + port+"】");
            BootNettyClientThread thread = new BootNettyClientThread(host,port);
            thread.start();
        }
    }
}