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
| package com.huafu.basecommon.netty;
import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.huafu.basecommon.netty.codec.NettyDecoder; import com.huafu.basecommon.netty.codec.NettyEncoder; import com.huafu.basecommon.netty.codec.SimpleProtocolDecoder; import com.huafu.basecommon.netty.codec.SimpleProtocolEncoder; import com.huafu.basecommon.netty.config.NettyServerConfig; import com.huafu.basecommon.netty.enums.MsgType; import com.huafu.basecommon.netty.exceptions.RemoteException; import com.huafu.basecommon.netty.handler.NettyServerHandler; import com.huafu.basecommon.netty.handler.SimpleServerHander; import com.huafu.basecommon.netty.processor.NettyRequestProcessor; import com.huafu.basecommon.netty.utils.Constants; import com.huafu.basecommon.netty.utils.NettyUtils; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.channel.epoll.Epoll; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.handler.timeout.IdleStateHandler; import lombok.extern.slf4j.Slf4j;
import java.nio.charset.StandardCharsets; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean;
@Slf4j public class NettyRemotingServer {
private final ServerBootstrap serverBootstrap = new ServerBootstrap();
private final ExecutorService defaultExecutor = Executors.newFixedThreadPool(Constants.CPUS);
private final EventLoopGroup bossGroup;
private final EventLoopGroup workGroup;
private final NettyServerConfig serverConfig;
private final NettyServerHandler serverHandler = new NettyServerHandler(this);
private final AtomicBoolean isStarted = new AtomicBoolean(false);
private static final String NETTY_BIND_FAILURE_MSG = "NettyRemotingServer bind %s fail";
public NettyRemotingServer(final NettyServerConfig serverConfig) { this.serverConfig = serverConfig; ThreadFactory bossThreadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("NettyServerBossThread_%s").build(); ThreadFactory workerThreadFactory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("NettyServerWorkerThread_%s").build(); if (Epoll.isAvailable()) { this.bossGroup = new EpollEventLoopGroup(1, bossThreadFactory); this.workGroup = new EpollEventLoopGroup(serverConfig.getWorkerThread(), workerThreadFactory); } else { this.bossGroup = new NioEventLoopGroup(1, bossThreadFactory); this.workGroup = new NioEventLoopGroup(serverConfig.getWorkerThread(), workerThreadFactory); } }
public void start() { if (isStarted.compareAndSet(false, true)) { this.serverBootstrap .group(this.bossGroup, this.workGroup) .channel(NettyUtils.getServerSocketChannelClass()) .option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.SO_BACKLOG, serverConfig.getSoBacklog()) .childOption(ChannelOption.SO_KEEPALIVE, serverConfig.isSoKeepalive()) .childOption(ChannelOption.TCP_NODELAY, serverConfig.isTcpNoDelay()) .childOption(ChannelOption.SO_SNDBUF, serverConfig.getSendBufferSize()) .childOption(ChannelOption.SO_RCVBUF, serverConfig.getReceiveBufferSize()) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) {
initNettyChannel(ch); } });
ChannelFuture future; try { future = serverBootstrap.bind(serverConfig.getListenPort()).sync(); } catch (Exception e) { log.error("NettyRemotingServer bind fail {}, exit", e.getMessage(), e); throw new RemoteException(String.format(NETTY_BIND_FAILURE_MSG, serverConfig.getListenPort())); }
future.addListener((ChannelFutureListener) cf -> { if (cf.isSuccess()) { log.info("NettyRemotingServer bind success at port : {}", serverConfig.getListenPort()); } else if (cf.cause() != null) { throw new RemoteException(String.format(NETTY_BIND_FAILURE_MSG, serverConfig.getListenPort()), future.cause()); } else { throw new RemoteException(String.format(NETTY_BIND_FAILURE_MSG, serverConfig.getListenPort())); } });
} }
private void initNettyChannel(SocketChannel ch) { ch.pipeline() .addLast("encoder", new NettyEncoder()) .addLast("decoder", new NettyDecoder())
.addLast("server-idle-handle", new IdleStateHandler(0, 0, Constants.NETTY_SERVER_HEART_BEAT_TIME, TimeUnit.MILLISECONDS)) .addLast("handler", serverHandler);
}
private void initNettyChannelBySimple(SocketChannel ch) { ch.pipeline() .addLast("encoder", new SimpleProtocolEncoder()) .addLast("decoder", new SimpleProtocolDecoder(1024, 0, 4, 0, 0, true)) .addLast("server-idle-handle", new IdleStateHandler(0, 0, Constants.NETTY_SERVER_HEART_BEAT_TIME, TimeUnit.MILLISECONDS)) .addLast("handler", new SimpleServerHander());
}
private void initNettyChannelByByte(SocketChannel ch) { ch.pipeline() .addLast("server-idle-handle", new IdleStateHandler(0, 0, Constants.NETTY_SERVER_HEART_BEAT_TIME, TimeUnit.MILLISECONDS)) .addLast(new SimpleChannelInboundHandler<ByteBuf>() { @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { System.out.println("Server received: " + msg.toString(StandardCharsets.UTF_8)); ctx.writeAndFlush(Unpooled.copiedBuffer("hello client", StandardCharsets.UTF_8)); } }); }
public void registerProcessor(final MsgType msgType, final NettyRequestProcessor processor) { this.registerProcessor(msgType, processor, null); }
public void registerProcessor(final MsgType msgType, final NettyRequestProcessor processor, final ExecutorService executor) { this.serverHandler.registerProcessor(msgType, processor, executor); }
public ExecutorService getDefaultExecutor() { return defaultExecutor; }
public void close() { if (isStarted.compareAndSet(true, false)) { try { if (bossGroup != null) { this.bossGroup.shutdownGracefully(); } if (workGroup != null) { this.workGroup.shutdownGracefully(); } defaultExecutor.shutdown(); } catch (Exception ex) { log.error("netty server close exception", ex); } log.info("netty server closed"); } } }
|