zm
2020-05-18 a18bfacbf56b401f6e0fdae8710fbca4df8cff77
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package com.codingapi.tx.netty.service.impl;
 
import com.codingapi.tx.Constants;
import com.codingapi.tx.framework.utils.SocketManager;
import com.codingapi.tx.netty.handler.TransactionHandler;
import com.codingapi.tx.netty.service.NettyControlService;
import com.codingapi.tx.netty.service.NettyDistributeService;
import com.codingapi.tx.netty.service.NettyService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
 
/**
 * Created by lorne on 2017/6/30.
 */
@Service
public class NettyServiceImpl implements NettyService ,DisposableBean {
 
 
    @Autowired
    private NettyDistributeService nettyDistributeService;
 
 
    @Autowired
    private NettyControlService nettyControlService;
 
 
    private EventLoopGroup workerGroup;
 
 
    private static volatile boolean isStarting = false;
 
 
    private Logger logger = LoggerFactory.getLogger(NettyServiceImpl.class);
 
    private ExecutorService threadPool = Executors.newFixedThreadPool(100);
 
    @Override
    public synchronized void start() {
        if (isStarting) {
            return;
        }
        isStarting = true;
        nettyDistributeService.loadTxServer();
 
        String host = Constants.txServer.getHost();
        int port = Constants.txServer.getPort();
        final int heart = Constants.txServer.getHeart();
        int delay = Constants.txServer.getDelay();
 
        final TransactionHandler transactionHandler = new TransactionHandler(threadPool,nettyControlService, delay);
        workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap(); // (1)
            b.group(workerGroup); // (2)
            b.channel(NioSocketChannel.class); // (3)
            b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
 
                    ch.pipeline().addLast("timeout", new IdleStateHandler(heart, heart, heart, TimeUnit.SECONDS));
 
                    ch.pipeline().addLast(new LengthFieldPrepender(4, false));
                    ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
 
                    ch.pipeline().addLast(transactionHandler);
                }
            });
            // Start the client.
            logger.info("connection txManager-socket-> host:" + host + ",port:" + port);
            ChannelFuture future = b.connect(host, port); // (5)
 
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (!channelFuture.isSuccess()) {
                        channelFuture.channel().eventLoop().schedule(new Runnable() {
                            @Override
                            public void run() {
                                isStarting = false;
                                start();
                            }
                        }, 5, TimeUnit.SECONDS);
                    }
                }
            });
 
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage());
        }
    }
 
    @Override
    public synchronized void close() {
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
            workerGroup = null;
 
            SocketManager.getInstance().setNetState(false);
            isStarting = false;
        }
    }
 
 
    @Override
    public boolean checkState() {
        if (!SocketManager.getInstance().isNetState()) {
            logger.error("socket not connection wait 2 seconds.");
            try {
                Thread.sleep(1000 * 2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (!SocketManager.getInstance().isNetState()) {
                logger.error("socket not connection,check txManager server .");
                return false;
            }
        }
 
        return true;
    }
 
 
    @Override
    public void destroy() throws Exception {
        close();
        SocketManager.getInstance().close();
        threadPool.shutdown();
    }
}