1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.shardingsphere.proxy.frontend.netty;
19
20 import io.netty.channel.ChannelHandlerContext;
21 import io.netty.channel.ChannelInboundHandlerAdapter;
22 import lombok.RequiredArgsConstructor;
23 import lombok.extern.slf4j.Slf4j;
24 import org.apache.shardingsphere.proxy.frontend.connection.ConnectionLimitContext;
25 import org.apache.shardingsphere.infra.exception.dialect.exception.connection.TooManyConnectionsException;
26 import org.apache.shardingsphere.proxy.frontend.spi.DatabaseProtocolFrontendEngine;
27
28
29
30
31 @RequiredArgsConstructor
32 @Slf4j
33 public class FrontendChannelLimitationInboundHandler extends ChannelInboundHandlerAdapter {
34
35 private final DatabaseProtocolFrontendEngine databaseProtocolFrontendEngine;
36
37 @Override
38 public void channelActive(final ChannelHandlerContext ctx) {
39 if (ConnectionLimitContext.getInstance().connectionAllowed()) {
40 ctx.fireChannelActive();
41 return;
42 }
43 log.debug("Closing channel {} due to the number of server connections has reached max connections {}", ctx.channel().remoteAddress(), ConnectionLimitContext.getInstance().getMaxConnections());
44
45 ctx.writeAndFlush(databaseProtocolFrontendEngine.getCommandExecuteEngine().getErrorPacket(new TooManyConnectionsException()));
46 ctx.close();
47 }
48
49 @Override
50 public void channelInactive(final ChannelHandlerContext ctx) {
51 ctx.fireChannelInactive();
52 ConnectionLimitContext.getInstance().connectionInactive();
53 }
54 }