hefeixia
2021-02-18 5b8c95c760840f09910730943b21391e47187315
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package chat.server.netty;
 
import static io.netty.channel.ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE;
 
import java.util.concurrent.TimeUnit;
 
import org.apache.log4j.Logger;
 
import chat.consts.BrokerConstants;
import chat.server.Configer;
import chat.server.moquette.BytesMetricsCollector;
import chat.server.moquette.MessageMetricsCollector;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
 
public class NettyAcceptor {
 
    private static Logger logger;
    
    private static NettyAcceptor instance;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    
    private Class<? extends ServerSocketChannel> channelClass;
    private ChannelFuture httpChannelFuture;
    private ChannelFuture tcpChannelFuture;
    private ChannelFuture sslTCPChannelFuture;
    private ChannelFuture wsChannelFuture;
    
    private MessageMetricsCollector messageMetricsCollector;
    private BytesMetricsCollector bytesMetricsCollector;
 
    
    static {
        logger = Logger.getLogger(NettyAcceptor.class);
    }
    
    private NettyAcceptor() {
        
    }
    
    public static synchronized NettyAcceptor getInstance() {
        if (instance == null) {
            instance = new NettyAcceptor();
        }
        
        return instance;
    }
    
    public static void start() throws Exception {
        instance = getInstance();
        instance.doStart();
    }
    
    public static void stop() {
        try {
            instance = getInstance();
            instance.doStop();
        }
        catch(Exception e) {
            logger.error(e);
        }
    }
    
    public void doStart() throws Exception {
        logger.info("Initializing Netty acceptor...");
        
        //1.
        initLocalVariable();
        
        //2. HTTP 短连接
        initializeHttpTransport();
        
        //3. TCP 长连接
        initializePlainTCPTransport();
        
        //4. SSL 长连接
        initializeSSLTCPTransport();
        
        //5. WebSocket 长连接
        initializeWSSTransport();
        
        logger.info("Netty acceptor initialized");
    }
    
    public void doStop() {
        logger.info("Closing Netty acceptor...");
        
        //1.
        closeOneChannel(httpChannelFuture);
        closeOneChannel(tcpChannelFuture);
        closeOneChannel(sslTCPChannelFuture);
        closeOneChannel(wsChannelFuture);
        
        //2.
        closeOneEventLoopGroup("worker group", workerGroup);
        closeOneEventLoopGroup("boss group", bossGroup);
    }
 
    private void initLocalVariable() {
        //1. 
        boolean epoll = Configer.getBoolean(BrokerConstants.NETTY_EPOLL_PROPERTY_NAME, false);
        if (epoll) {
            // 由于目前只支持TCP MQTT, 所以bossGroup的线程数配置为1
            logger.info("Netty is using Epoll");
            bossGroup = new EpollEventLoopGroup(1);
            workerGroup = new EpollEventLoopGroup();
            channelClass = EpollServerSocketChannel.class;
        } 
        else {
            logger.info("Netty is using NIO");
            bossGroup = new NioEventLoopGroup(1);
            workerGroup = new NioEventLoopGroup();
            channelClass = NioServerSocketChannel.class;
        }
        
        //2.
        bytesMetricsCollector = new BytesMetricsCollector();
        messageMetricsCollector = new MessageMetricsCollector();
    }
    
    private void initializeHttpTransport() throws Exception {
        String protocol = "HTTP";    
        Integer port = Configer.getInteger("http_port", null);
        
        if (port == null) {
            logger.info("skip server, Protocol=" + protocol);
            return;
        }
        
        //2. create bootstrap
        logger.info("Initializing server. Protocol=" + protocol);
        NettyHttpChannelInitializer initializer = new NettyHttpChannelInitializer();
        ServerBootstrap bootStrap = new NettyServerBootstrap(this, initializer);
        
        //3. Bind and start to accept incoming connections.
        httpChannelFuture = bootStrap.bind(port);    
        httpChannelFuture.sync().addListener(FIRE_EXCEPTION_ON_FAILURE);
        
        logger.info("server bounded. Protocol=" + protocol + ": " + port);
    }
 
    private void initializePlainTCPTransport() throws Exception {
        //1. load host and port
        String protocol = "TCP";
        Integer port = Configer.getInteger("port", null);
 
        if (port == null) {
            logger.info("skip server, Protocol=" + protocol);
            return;
        }
        
        //2. create bootstrap
        NettyTCPChannelInitializer initializer = new NettyTCPChannelInitializer();
        initializer.setMessageMetricsCollector(messageMetricsCollector);
        initializer.setBytesMetricsCollector(bytesMetricsCollector);
        
        ServerBootstrap bootStrap = new NettyServerBootstrap(this, initializer);
        
        //3. Bind and start to accept incoming connections.
        tcpChannelFuture = bootStrap.bind(port);    
        tcpChannelFuture.sync().addListener(FIRE_EXCEPTION_ON_FAILURE);  
        
        logger.info("server bounded. Protocol=" + protocol + ": " + port);
    }
 
    private void initializeSSLTCPTransport() throws InterruptedException {
        //1. load host and port
        String protocol = "SSL";
        Integer port = Configer.getInteger("ssl_port", null);
        
        if (port == null) {
            logger.info("skip server, Protocol=" + protocol);
            return;
        }
        
        //2. create bootstrap
        NettySSLChannelInitializer initializer = new NettySSLChannelInitializer();
        initializer.setMessageMetricsCollector(messageMetricsCollector);
        initializer.setBytesMetricsCollector(bytesMetricsCollector);
        
        ServerBootstrap bootStrap = new NettyServerBootstrap(this, initializer);
 
        //3. Bind and start to accept incoming connections.
        sslTCPChannelFuture = bootStrap.bind(port);    
        sslTCPChannelFuture.sync().addListener(FIRE_EXCEPTION_ON_FAILURE);  
        
        logger.info("server bounded. Protocol=" + protocol + ": " + port);
    }
    
    private void initializeWSSTransport() throws Exception {
        //1. load host and port 
        String protocol = "Secure Websocket";
        Integer port = Configer.getInteger("ws_port", null);
        
        if (port == null) {
            logger.info("skip server, Protocol=" + protocol);
            return;
        }
        
        //2. create bootstrap
        ChannelInitializer<SocketChannel> initializer = new NettyWSChannelInitializer();
        ServerBootstrap bootStrap = new NettyServerBootstrap(this, initializer);
 
        //3. Bind and start to accept incoming connections.
        wsChannelFuture = bootStrap.bind(port);    
        wsChannelFuture.sync().addListener(FIRE_EXCEPTION_ON_FAILURE);  
        
        logger.info("server bounded. Protocol=" + protocol + ": " + port);
    }
    
    private void closeOneChannel(ChannelFuture channelFuture) {
        if (channelFuture == null) {
            return;
        }
            
        Channel channel = channelFuture.channel();
        try {
            channel.close();
        } catch (Exception e) {
        }    
        
        try {
            channel.closeFuture().sync();
        } catch (Exception e) {
        }
    }
    
    private void closeOneEventLoopGroup(String name, EventLoopGroup loopGroup) {
        if (loopGroup == null) {
            return;
        }
        
        //1. close gracefully
        Future<?> waiter = loopGroup.shutdownGracefully();
 
        logger.info("Waiting for" + name + " event loop groups to terminate...");
        try {
            waiter.await(3, TimeUnit.SECONDS);
        } 
        catch (InterruptedException iex) {
            logger.warn("An InterruptedException was caught while waiting for event loops to terminate...");
        }
        
        //2. close force
        if (!loopGroup.isTerminated()) {
            logger.warn("Forcing shutdown " + name + "...");
            loopGroup.shutdownGracefully(0L, 0L, TimeUnit.MILLISECONDS);
        }
    }
 
    public EventLoopGroup getBossGroup() {
        return bossGroup;
    }
 
    public EventLoopGroup getWorkerGroup() {
        return workerGroup;
    }
 
    public Class<? extends ServerSocketChannel> getChannelClass() {
        return channelClass;
    }
 
}