/** * 启动netty客户端 */ @Override public void start(TxConfig txConfig) { this.txConfig = txConfig; SerializeProtocolEnum serializeProtocol = SerializeProtocolEnum.acquireSerializeProtocol(txConfig.getNettySerializer()); nettyClientHandlerInitializer.setSerializeProtocolEnum(serializeProtocol); servletExecutor = new DefaultEventExecutorGroup(txConfig.getNettyThreadMax()); nettyClientHandlerInitializer.setServletExecutor(servletExecutor); nettyClientHandlerInitializer.setTxConfig(txConfig); TxManagerLocator.getInstance().setTxConfig(txConfig); TxManagerLocator.getInstance().schedulePeriodicRefresh(); try { bootstrap = new Bootstrap(); groups(bootstrap, txConfig.getNettyThreadMax()); doConnect(); } catch (Exception e) { e.printStackTrace(); } }
public Server(StartupContext startupContext) throws Exception { BrokerConfigProvider configProvider = startupContext.getService(BrokerConfigProvider.class); this.configuration = configProvider .getConfigurationObject(AmqpServerConfiguration.NAMESPACE, AmqpServerConfiguration.class); this.broker = startupContext.getService(Broker.class); if (broker == null) { throw new RuntimeException("Could not find the broker class to initialize AMQP server"); } bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); ioExecutors = new DefaultEventExecutorGroup(BLOCKING_TASK_EXECUTOR_THREADS); haStrategy = startupContext.getService(HaStrategy.class); if (haStrategy == null) { serverHelper = new ServerHelper(); } else { LOGGER.info("AMQP Transport is in PASSIVE mode"); //starts up in passive mode serverHelper = new HaEnabledServerHelper(); } }
@Override public void start() throws EmbeddedServletContainerException { ServerBootstrap b = new ServerBootstrap(); groups(b); servletExecutor = new DefaultEventExecutorGroup(50); b.childHandler(new NettyEmbeddedServletInitializer(servletExecutor, context)); // Don't yet need the complexity of lifecycle state, listeners etc, so tell the context it's initialised here context.setInitialised(true); ChannelFuture future = b.bind(address).awaitUninterruptibly(); //noinspection ThrowableResultOfMethodCallIgnored Throwable cause = future.cause(); if (null != cause) { throw new EmbeddedServletContainerException("Could not start Netty server", cause); } logger.info(context.getServerInfo() + " started on port: " + getPort()); }
public void start(int listenPort, final ExecutorService ignore) throws Exception { if (!startFlag.compareAndSet(false, true)) { return; } bossGroup = new NioEventLoopGroup(); ioGroup = new NioEventLoopGroup(); businessGroup = new DefaultEventExecutorGroup(businessThreads); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, ioGroup).channel(NioServerSocketChannel.class) .childOption(ChannelOption.TCP_NODELAY, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.nodelay", "true"))) .childOption(ChannelOption.SO_REUSEADDR, Boolean.parseBoolean(System.getProperty("nfs.rpc.tcp.reuseaddress", "true"))) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("decoder", new Netty4ProtocolDecoder()); ch.pipeline().addLast("encoder", new Netty4ProtocolEncoder()); ch.pipeline().addLast(businessGroup, "handler", new Netty4ServerHandler()); } }); b.bind(new InetSocketAddress("127.0.0.1", listenPort)).sync(); LOGGER.warn("Server started,listen at: " + listenPort + ", businessThreads is " + businessThreads); }
public void initChannel(SocketChannel channel) { ChannelPipeline pipeline = channel.pipeline(); // pipeline.addLast("tracker", connectionTracker); pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("aggregator", new HttpObjectAggregator(Integer.MAX_VALUE)); //TODO: fix pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("compressor", new HttpContentCompressor()); HttpResourceHandler resourceHandler = new HttpResourceHandler(dataHolder.getHttpServices(), new ArrayList<HandlerHook>(), null, null); pipeline.addLast(new DefaultEventExecutorGroup(200), "router", new RequestRouter(resourceHandler, 0)); //TODO: remove limit //TODO: see what can be done /*if (pipelineModifier != null) { pipelineModifier.apply(pipeline); }*/ }
@Inject public ApiServerChannelInitializer(ObjectMapper objectMapper, ApiProtocolSwitcher apiProtocolSwitcher, // ObservableEncoder rxjavaHandler, GeneratedJaxRsModuleHandler jaxRsModuleHandler) { this.apiProtocolSwitcher = apiProtocolSwitcher; // this.rxjavaHandler = rxjavaHandler; this.jaxRsHandlers = jaxRsModuleHandler; SimpleModule nettyModule = new SimpleModule("Netty", PackageVersion.VERSION); nettyModule.addSerializer(new ByteBufSerializer()); objectMapper.registerModule(nettyModule); // TODO: allow customization of the thread pool! // rxJavaGroup = new DefaultEventExecutorGroup(4, new DefaultThreadFactory("rxjava")); jaxRsGroup = new DefaultEventExecutorGroup(Runtime.getRuntime().availableProcessors(), new DefaultThreadFactory("jax-rs")); }
public NettyStarter() throws InterruptedException { LOG.info("NettyHttpServer Initializing..."); bossGroup = new NioEventLoopGroup(); LOG.trace("NettyHttpServer bossGroup created."); workerGroup = new NioEventLoopGroup(); LOG.trace("NettyHttpServer workGroup created."); bServer = new ServerBootstrap(); LOG.trace("NettyHttpServer ServerBootstrap created."); eventExecutor = new DefaultEventExecutorGroup(1); LOG.trace("NettyHttpServer Task Executor created."); DefaultServerInitializer sInit = new DefaultServerInitializer(eventExecutor); LOG.trace("NettyHttpServer InitClass instance created."); LOG.trace("NettyHttpServer InitClass instance Init()."); bServer.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class).childHandler(sInit) .option(ChannelOption.SO_REUSEADDR, true); LOG.trace("NettyHttpServer ServerBootstrap group initialized."); bindChannel = bServer.bind(HTTP_BIND_PORT).sync().channel(); }
@Override public void init(String path, final int heartBeatInterval, final NetHandler netHandler, String threadName) throws Throwable { final Conf conf = new Conf(path); this.netHandler = netHandler; NioEventLoopGroup group = new NioEventLoopGroup(conf.getIothreadnum()); bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.SO_SNDBUF, conf.getSendBuf()).option(ChannelOption.SO_RCVBUF, conf.getRecvBuf()) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new IdleStateHandler((int) (2 * heartBeatInterval / 1000), 0, 0)); if (conf.getWorkthreadNum() == 0) { ch.pipeline().addLast(new BufDecoder(), new NettyHandler(netHandler)); } else { ch.pipeline().addLast(new DefaultEventExecutorGroup(conf.getWorkthreadNum()), new BufDecoder(), new NettyHandler(netHandler)); } } }); }
@Override public void init(String confPath, final int heartBeatInterval, final NetHandler handler,String ip,int port, String threadName) throws FileNotFoundException, IOException { final Conf conf = new Conf(confPath); this.ip = ip; this.port = port; NioEventLoopGroup group = new NioEventLoopGroup(conf.getIothreadnum()); bootstrap.group(group).channel(NioServerSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.SO_SNDBUF, conf.getSendBuf()).option(ChannelOption.SO_RCVBUF, conf.getRecvBuf()) .option(ChannelOption.SO_BACKLOG, conf.getBacklog()).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new IdleStateHandler((int) (2 * heartBeatInterval / 1000), 0, 0)); if (conf.getWorkthreadNum() == 0) { ch.pipeline().addLast(new BufDecoder(), new NettyHandler(handler)); } else { ch.pipeline().addLast(new DefaultEventExecutorGroup(conf.getWorkthreadNum()), new BufDecoder(), new NettyHandler(handler)); } } }); }
@Override public void start() throws Exception { int bossThreads = conf.getInt("netty.threads.Boss"); bossLoop = eventLoop(bossThreads, "boss"); int workerThreads = conf.getInt("netty.threads.Worker"); if (workerThreads > 0) { workerLoop = eventLoop(Math.max(4, workerThreads), "worker"); } else { workerLoop = bossLoop; } ThreadFactory threadFactory = new DefaultThreadFactory(conf.getString("netty.threads.Name")); this.executor = new DefaultEventExecutorGroup(conf.getInt("netty.threads.Max"), threadFactory); this.ch = bootstrap(executor, null, conf.getInt("application.port")); boolean securePort = conf.hasPath("application.securePort"); if (securePort) { bootstrap(executor, NettySslContext.build(conf), conf.getInt("application.securePort")); } }
/** * 启动netty服务 */ @Override public void start() { SocketManager.getInstance().setMaxConnection(nettyConfig.getMaxConnection()); servletExecutor = new DefaultEventExecutorGroup(MAX_THREADS); if (nettyConfig.getMaxThreads() != 0) { MAX_THREADS = nettyConfig.getMaxThreads(); } try { final SerializeProtocolEnum serializeProtocolEnum = SerializeProtocolEnum.acquireSerializeProtocol(nettyConfig.getSerialize()); nettyServerHandlerInitializer.setSerializeProtocolEnum(serializeProtocolEnum); nettyServerHandlerInitializer.setServletExecutor(servletExecutor); ServerBootstrap b = new ServerBootstrap(); groups(b, MAX_THREADS << 1); /* bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(MAX_THREADS * 2); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childHandler(nettyServerHandlerInitializer);*/ b.bind(nettyConfig.getPort()); LOGGER.info("netty service started on port: " + nettyConfig.getPort()); } catch (Exception e) { e.printStackTrace(); } }
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(nettyClientConfig.getClientWorkerThreads(),new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet()); } }); this.bootstrap .group(this.eventLoopGroupWorker) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_KEEPALIVE, false) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,nettyClientConfig.getConnectTimeoutMillis()) .option(ChannelOption.SO_SNDBUF,nettyClientConfig.getClientSocketSndBufSize()) .option(ChannelOption.SO_RCVBUF,nettyClientConfig.getClientSocketRcvBufSize()) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { // 编码 ch.pipeline().addLast(new NettyEncoder(serializeTypeCurrentRPC)); // 解码 ch.pipeline().addLast(new NettyDecoder(RemotingCommand.class,serializeTypeCurrentRPC)); // 心跳 ch.pipeline().addLast(new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds())); // 业务处理 ch.pipeline().addLast(defaultEventExecutorGroup,new NettyConnectManageHandler(), new NettyClientHandler()); } }); }
@Default default EventExecutorGroup executor() { Logger logger = LoggerFactory.getLogger("imap-executor"); ThreadFactory threadFactory = new ThreadFactoryBuilder() .setDaemon(true) .setUncaughtExceptionHandler((t, e) -> logger.error("Uncaught exception on thread {}", t.getName(), e)) .setNameFormat("imap-executor-%d") .build(); int nThreads = Runtime.getRuntime().availableProcessors() * 2; return new DefaultEventExecutorGroup(nThreads, threadFactory); }
public void start() throws IOException, InterruptedException, URISyntaxException { // Server part mBossGroup = new NioEventLoopGroup(); mWorkerGroup = new NioEventLoopGroup(); mExecutorGroup = new DefaultEventExecutorGroup(Integer.parseInt(mServer.getConfig().getProperty("netty.executor_threads", "512"))); ServerBootstrap b = new ServerBootstrap(); b.group(mBossGroup, mWorkerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ClientInitializer(mServer, mExecutorGroup)); int port = Integer.parseInt(mServer.getConfig().getProperty("server.port")); mChannel = b.bind(port).sync().channel(); Server.LOGGER.info("Server started on port " + port + "."); }
@Override protected void initChannel(SocketChannel socketChannel) throws Exception { final EventExecutorGroup group = new DefaultEventExecutorGroup(Runtime.getRuntime().availableProcessors() + 1); socketChannel.pipeline().addLast(new CommonEncoder()); socketChannel.pipeline().addLast(new CommonDecoder()); socketChannel.pipeline().addLast(group, new CommonServiceHandler(accessService)); }
private void switchToHttp(ChannelHandlerContext ctx) { ChannelPipeline p = ctx.pipeline(); p.addLast(new HttpServerCodec()); p.addLast(new HttpObjectAggregator(MAX_CONTENT_LENGTH)); p.addLast(new ChunkedWriteHandler()); p.addLast(new ServletContentHandler(context,ctx.channel())); p.addLast(new DefaultEventExecutorGroup(THREAD_SIZE),requestDispatcherHandler); }
@Override public void init(Configuration configuration) { components = new Components(); components.init(configuration); initHandler(); host = configuration.getString(Configurations.CFG_BIND_HOST, Configurations.DEFAULT_BIND_HOST); port = configuration.getInteger(Configurations.CFG_BIND_PORT, Configurations.DEFAULT_BIND_PORT); int bossCore = configuration.getInteger(Configurations.CFG_BOSS_CORE, Configurations.DEFAULT_BOSS_CORE); int workerCore = configuration.getInteger(Configurations.CFG_WORKER_CORE, Configurations.DEFAULT_WORKER_CORE); boss = new NioEventLoopGroup(bossCore); worker = new NioEventLoopGroup(workerCore); businessGroup = new DefaultEventExecutorGroup(Runtime.getRuntime().availableProcessors()); }
@Override protected void clientStart() throws RemotingException { NettyLogger.setNettyLoggerFactory(); this.defaultEventExecutorGroup = new DefaultEventExecutorGroup( remotingClientConfig.getClientWorkerThreads(), new NamedThreadFactory("NettyClientWorkerThread_") ); final NettyCodecFactory nettyCodecFactory = new NettyCodecFactory(getCodec()); this.bootstrap.group(this.eventLoopGroup).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( defaultEventExecutorGroup, nettyCodecFactory.getEncoder(), nettyCodecFactory.getDecoder(), new IdleStateHandler(remotingClientConfig.getReaderIdleTimeSeconds(), remotingClientConfig.getWriterIdleTimeSeconds(), remotingClientConfig.getClientChannelMaxIdleTimeSeconds()),// new NettyConnectManageHandler(), new NettyClientHandler()); } }); }
@Override protected void serverStart() throws RemotingException { NettyLogger.setNettyLoggerFactory(); this.defaultEventExecutorGroup = new DefaultEventExecutorGroup( remotingServerConfig.getServerWorkerThreads(), new NamedThreadFactory("NettyServerWorkerThread_") ); final NettyCodecFactory nettyCodecFactory = new NettyCodecFactory(getCodec()); this.serverBootstrap.group(this.bossSelectorGroup, this.workerSelectorGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 65536) .option(ChannelOption.SO_REUSEADDR, true) .childOption(ChannelOption.TCP_NODELAY, true) .localAddress(new InetSocketAddress(this.remotingServerConfig.getListenPort())) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( defaultEventExecutorGroup, nettyCodecFactory.getEncoder(), nettyCodecFactory.getDecoder(), new IdleStateHandler(remotingServerConfig.getReaderIdleTimeSeconds(), remotingServerConfig.getWriterIdleTimeSeconds(), remotingServerConfig.getServerChannelMaxIdleTimeSeconds()),// new NettyConnectManageHandler(), // new NettyServerHandler()); } }); try { this.serverBootstrap.bind().sync(); } catch (InterruptedException e) { throw new RemotingException("Start Netty server bootstrap error", e); } }
protected EventExecutorGroup createExecutorService() { // Provide the executor service for the application // and use a Camel thread factory so we have consistent thread namings // we should use a shared thread pool as recommended by Netty String pattern = getCamelContext().getExecutorServiceManager().getThreadNamePattern(); ThreadFactory factory = new CamelThreadFactory(pattern, "NettyEventExecutorGroup", true); return new DefaultEventExecutorGroup(getMaximumPoolSize(), factory); }
@BeforeClass public static void createGroup() { logger.info("Bandwidth: " + minfactor + " <= " + bandwidthFactor + " <= " + maxfactor + " StepMs: " + stepms + " MinMs: " + minimalms + " CheckMs: " + check); group = new DefaultEventExecutorGroup(8); groupForGlobal = new DefaultEventExecutorGroup(8); }
public static void modifyPipeline() { ChannelPipeline ch = null; FirstHandler firstHandler = new FirstHandler(); ch.addLast("handler1", firstHandler); ch.addFirst("handler2", new SecondHandler()); ch.addLast("handler3", new ThirdHandler()); ch.addLast(new DefaultEventExecutorGroup(10), new ThirdHandler()); ch.remove("handler3"); ch.remove(firstHandler); ch.replace("handler2", "handler4", new ForthHandler()); }
@Override @SuppressWarnings("unchecked") public void execute() throws MojoExecutionException, MojoFailureException { DefaultEventExecutorGroup group = (DefaultEventExecutorGroup) getPluginContext().get(StartRedisMojo.REDIS_GROUP_CONTEXT_PROPERTY_NAME); if(group == null) { throw new MojoExecutionException("Redis server is not running"); } getLog().info("Shutting down Redis server..."); group.shutdownGracefully(); }
public void setServletExecutor(DefaultEventExecutorGroup servletExecutor) { this.servletExecutor = servletExecutor; }
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(// nettyClientConfig.getClientWorkerThreads(), // new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet()); } }); this.bootstrap.group(this.eventLoopGroupWorker).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_SNDBUF, NettySystemConfig.SocketSndbufSize) .option(ChannelOption.SO_RCVBUF, NettySystemConfig.SocketRcvbufSize) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(defaultEventExecutorGroup, // encoder, // decoder, // new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()),// new NettyConnetManageHandler(), // handler); } }); // 每隔1秒扫描下异步调用超时情况 this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRemotingClient.this.scanResponseTable(); } catch (Exception e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); }
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(// nettyServerConfig.getServerWorkerThreads(), // new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "NettyServerWorkerThread_" + this.threadIndex.incrementAndGet()); } }); ServerBootstrap childHandler = // this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupWorker) .channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024) .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_SNDBUF, NettySystemConfig.SocketSndbufSize) .childOption(ChannelOption.SO_RCVBUF, NettySystemConfig.SocketRcvbufSize) .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort())) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( // defaultEventExecutorGroup, // encoder, // decoder, // new IdleStateHandler(0, 0, nettyServerConfig .getServerChannelMaxIdleTimeSeconds()),// new NettyConnetManageHandler(), // handler); } }); if (NettySystemConfig.NettyPooledByteBufAllocatorEnable) { childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); } try { ChannelFuture sync = this.serverBootstrap.bind().sync(); InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress(); this.port = addr.getPort(); } catch (InterruptedException e1) { throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1); } // 每隔1秒扫描下异步调用超时情况 this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRemotingServer.this.scanResponseTable(); } catch (Exception e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); }
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(// nettyClientConfig.getClientWorkerThreads(), // new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet()); } }); //netty客户端 Bootstrap handler = this.bootstrap.group(this.eventLoopGroupWorker).channel(NioSocketChannel.class)// .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_KEEPALIVE, false) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyClientConfig.getConnectTimeoutMillis()) .option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize()) .option(ChannelOption.SO_RCVBUF, nettyClientConfig.getClientSocketRcvBufSize()) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( defaultEventExecutorGroup, new NettyEncoder(), //编码 new NettyDecoder(), //解码 new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()), //心跳检查 new NettyConnectManageHandler(), new NettyClientHandler()); } }); this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRemotingClient.this.scanResponseTable(); } catch (Exception e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); if (this.channelEventListener != null) { this.nettyEventExecutor.start(); } }
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup( nettyServerConfig.getServerWorkerThreads(), new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet()); } }); //netty 服务端 ServerBootstrap childHandler = this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupSelector) //这里指定EpollServerSocketChannel或者NioServerSocketChannel类初始化channel用来接受客户端请求。 .channel(useEpoll() ? EpollServerSocketChannel.class : NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.SO_KEEPALIVE, false) .childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize()) .childOption(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize()) .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort())) //前面有设置nettyServerConfig.setListenPort(9876)操作 //通常会为新SocketChannel通过添加一些handler,来设置ChannelPipeline。ChannelInitializer 是一个特殊的handler,其中initChannel方法可以为SocketChannel 的pipeline添加指定handler。 .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( defaultEventExecutorGroup, new NettyEncoder(), //编码 new NettyDecoder(), //解码 new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), //心跳检查 new NettyConnectManageHandler(), new NettyServerHandler()); } }); if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) { // 这个选项有可能会占用大量堆外内存,暂时不使用。 childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); } try { ChannelFuture sync = this.serverBootstrap.bind().sync();//通过绑定,就可以对外提供服务了。 InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress(); this.port = addr.getPort(); //奇怪为什么没有关闭???? 类似这样的 sync.channel().closeFuture().sync(); } catch (InterruptedException e1) { throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1); } if (this.channelEventListener != null) { this.nettyEventExecutor.start(); } // 每隔1秒扫描下异步调用超时情况 this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRemotingServer.this.scanResponseTable(); } catch (Exception e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); }
@Override public void start() { //MQClientAPIImpl.start中执行 //MQClientInstance.start->MQClientAPIImpl.start->NettyRemotingClient.start this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(// nettyClientConfig.getClientWorkerThreads(), // new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet()); } }); Bootstrap handler = this.bootstrap.group(this.eventLoopGroupWorker).channel(NioSocketChannel.class)// // .option(ChannelOption.TCP_NODELAY, true) // .option(ChannelOption.SO_KEEPALIVE, false) // .option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize()) // .option(ChannelOption.SO_RCVBUF, nettyClientConfig.getClientSocketRcvBufSize()) // .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(// defaultEventExecutorGroup, // new NettyEncoder(), // new NettyDecoder(), // new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()),// new NettyConnetManageHandler(), // new NettyClientHandler()); } }); //延迟3秒, 一秒扫一次resposneTable, 通过回调函数处理response. client 异步拉取消息的处理也是在这里完成。 this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { //定时扫描 NettyRemotingClient.this.scanResponseTable(); } catch (Exception e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); //用于处理nettyEvent. if (this.channelEventListener != null) { this.nettyEventExecuter.start(); } }
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(// nettyServerConfig.getServerWorkerThreads(), // new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet()); } }); ServerBootstrap childHandler = // this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupSelector).channel(NioServerSocketChannel.class) // .option(ChannelOption.SO_BACKLOG, 1024) // .option(ChannelOption.SO_REUSEADDR, true) // .option(ChannelOption.SO_KEEPALIVE, false) // .childOption(ChannelOption.TCP_NODELAY, true) // .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize()) // .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize()) // .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort())) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( // defaultEventExecutorGroup, // new NettyEncoder(), // new NettyDecoder(), // new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()),// new NettyConnetManageHandler(), // new NettyServerHandler()); } }); if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) { childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); } try { ChannelFuture sync = this.serverBootstrap.bind().sync(); InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress(); this.port = addr.getPort(); } catch (InterruptedException e1) { throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1); } if (this.channelEventListener != null) { this.nettyEventExecuter.start(); } this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRemotingServer.this.scanResponseTable(); } catch (Exception e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); }
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(// nettyClientConfig.getClientWorkerThreads(), // new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet()); } }); Bootstrap handler = this.bootstrap.group(this.eventLoopGroupWorker).channel(NioSocketChannel.class)// // .option(ChannelOption.TCP_NODELAY, true) // .option(ChannelOption.SO_KEEPALIVE, false) // .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyClientConfig.getConnectTimeoutMillis()) // .option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize()) // .option(ChannelOption.SO_RCVBUF, nettyClientConfig.getClientSocketRcvBufSize()) // .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(// defaultEventExecutorGroup, // new NettyEncoder(), // new NettyDecoder(), // new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()), // new NettyConnetManageHandler(), // new NettyClientHandler()); } }); this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRemotingClient.this.scanResponseTable(); } catch (Exception e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); if (this.channelEventListener != null) { this.nettyEventExecuter.start(); } }
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(// nettyServerConfig.getServerWorkerThreads(), // new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet()); } }); ServerBootstrap childHandler = // this.serverBootstrap.group(this.eventLoopGroupBoss, this.eventLoopGroupSelector).channel(NioServerSocketChannel.class) // .option(ChannelOption.SO_BACKLOG, 1024) // .option(ChannelOption.SO_REUSEADDR, true) // .option(ChannelOption.SO_KEEPALIVE, false) // .childOption(ChannelOption.TCP_NODELAY, true) // .option(ChannelOption.SO_SNDBUF, nettyServerConfig.getServerSocketSndBufSize()) // .option(ChannelOption.SO_RCVBUF, nettyServerConfig.getServerSocketRcvBufSize()) // .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort())) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( defaultEventExecutorGroup, // new NettyEncoder(), // new NettyDecoder(), // new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds()), // new NettyConnetManageHandler(), // new NettyServerHandler()); } }); if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) { childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); } try { ChannelFuture sync = this.serverBootstrap.bind().sync(); InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress(); this.port = addr.getPort(); } catch (InterruptedException e1) { throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1); } if (this.channelEventListener != null) { this.nettyEventExecuter.start(); } this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRemotingServer.this.scanResponseTable(); } catch (Exception e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); }
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(nettyServerConfig.getServerWorkerThreads(),new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "NettyServerCodecThread_" + this.threadIndex.incrementAndGet()); } }); ServerBootstrap childHandler = this.serverBootstrap .group(this.eventLoopGroupBoss, this.eventLoopGroupSelector) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.SO_KEEPALIVE, false) .childOption(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_SNDBUF,nettyServerConfig.getServerSocketSndBufSize()) .option(ChannelOption.SO_RCVBUF,nettyServerConfig.getServerSocketRcvBufSize()) .localAddress(new InetSocketAddress(this.nettyServerConfig.getListenPort())) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { //编码 ch.pipeline().addLast(new NettyEncoder(serializeTypeCurrentRPC)); //解码 ch.pipeline().addLast(new NettyDecoder(RemotingCommand.class,serializeTypeCurrentRPC)); //心跳 ch.pipeline().addLast(new IdleStateHandler(0, 0, nettyServerConfig.getServerChannelMaxIdleTimeSeconds())); //业务处理 ch.pipeline().addLast(defaultEventExecutorGroup,new NettyConnetManageHandler(),new NettyServerHandler()); } }); if (nettyServerConfig.isServerPooledByteBufAllocatorEnable()) { childHandler.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); } try { ChannelFuture sync = this.serverBootstrap.bind().sync(); InetSocketAddress addr = (InetSocketAddress) sync.channel().localAddress(); this.port = addr.getPort(); log.info("netty server already started!monitor at port {}",this.port); } catch (InterruptedException e1) { throw new RuntimeException("this.serverBootstrap.bind().sync() InterruptedException", e1); } }
private static synchronized EventExecutorGroup initEventExecutors() { if(serializeEventGroup != null) return serializeEventGroup; NamedThreadFactory threadName = new NamedThreadFactory("JSF-SERIALIZE-W ", true); return new DefaultEventExecutorGroup(30, threadName); }
@Override public void start() { this.defaultEventExecutorGroup = new DefaultEventExecutorGroup(// nettyClientConfig.getClientWorkerThreads(), // new ThreadFactory() { private AtomicInteger threadIndex = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "NettyClientWorkerThread_" + this.threadIndex.incrementAndGet()); } }); Bootstrap handler = this.bootstrap.group(this.eventLoopGroupWorker).channel(NioSocketChannel.class)// .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_KEEPALIVE, false) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyClientConfig.getConnectTimeoutMillis()) .option(ChannelOption.SO_SNDBUF, nettyClientConfig.getClientSocketSndBufSize()) .option(ChannelOption.SO_RCVBUF, nettyClientConfig.getClientSocketRcvBufSize()) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( defaultEventExecutorGroup, new NettyEncoder(), new NettyDecoder(), new IdleStateHandler(0, 0, nettyClientConfig.getClientChannelMaxIdleTimeSeconds()), new NettyConnectManageHandler(), new NettyClientHandler()); } }); this.timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { NettyRemotingClient.this.scanResponseTable(); } catch (Exception e) { log.error("scanResponseTable exception", e); } } }, 1000 * 3, 1000); if (this.channelEventListener != null) { this.nettyEventExecuter.start(); } }
public DefaultServer(Class serverChannelClass, ChannelPipelineFactoryFactory factory, Set<String> channelOptions, int port, InetAddress address) { if (!ServerChannel.class.isAssignableFrom(serverChannelClass)) throw new RuntimeException( "serverChannelClass must implement ServerChannel"); // Configure the server. bootstrap = new ServerBootstrap(); _port = port; _address = address; internalGroup = new DefaultEventExecutorGroup(10); if (isNio(serverChannelClass)) { bossGroup = new NioEventLoopGroup(); childGroup = new NioEventLoopGroup(); } else if (isOio(serverChannelClass)) { bossGroup = new OioEventLoopGroup(); childGroup = new OioEventLoopGroup(); } else { bossGroup = new NioEventLoopGroup(); childGroup = new NioEventLoopGroup(); } bootstrap.group(bossGroup, childGroup); bootstrap.channel(serverChannelClass); // bootstrap.setOption("child.trafficClass", IPTOS_LOWDELAY); // bootstrap.setOption("child.tcpNoDelay", false); // bootstrap.childOption(ChannelOption.IP_TOS, IPTOS_THROUGHPUT); setChannelOptions(channelOptions); bootstrap.option(ChannelOption.SO_BACKLOG, 100); ChannelPipelineFactory channelPipelineFactory = factory.create( internalGroup, bootstrap); bootstrap.childHandler(channelPipelineFactory); }
protected AbstractReusedEventGroup(int ioThreads, String ioThreadName, int eventThreads, String eventThreadName) { this.reusedEventLoopGroup = NettyPlatformIndependent.newEventLoopGroup(ioThreads, new DefaultThreadFactory(ioThreadName)); this.reusedEventExecutorGroup = new DefaultEventExecutorGroup(eventThreads, new DefaultThreadFactory(eventThreadName)); }
public Builder executorGroupThreadPoll(int threads) { this.eventExecutorGroup = new DefaultEventExecutorGroup(threads); return this; }