List of usage examples for io.netty.handler.traffic GlobalTrafficShapingHandler GlobalTrafficShapingHandler
public GlobalTrafficShapingHandler(ScheduledExecutorService executor, long writeLimit, long readLimit)
From source file:cc.agentx.server.net.nio.XServer.java
License:Apache License
public void start() { Configuration config = Configuration.INSTANCE; InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE); EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*from ww w . jav a 2 s . co m*/ ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast("logging", new LoggingHandler(LogLevel.DEBUG)) .addLast(new XConnectHandler()); if (config.getReadLimit() != 0 || config.getWriteLimit() != 0) { socketChannel.pipeline().addLast( new GlobalTrafficShapingHandler(Executors.newScheduledThreadPool(1), config.getWriteLimit(), config.getReadLimit())); } } }); log.info("\tStartup {}-{}-server [{}]", Constants.APP_NAME, Constants.APP_VERSION, config.getProtocol()); ChannelFuture future = bootstrap.bind(config.getHost(), config.getPort()).sync(); future.addListener(future1 -> log.info("\tListening at {}:{}...", config.getHost(), config.getPort())); future.channel().closeFuture().sync(); } catch (Exception e) { log.error("\tSocket bind failure ({})", e.getMessage()); } finally { log.info("\tShutting down and recycling..."); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); Configuration.shutdownRelays(); } System.exit(0); }
From source file:de.jackwhite20.apex.Apex.java
License:Open Source License
public void start(Mode mode) { commandManager.addCommand(new HelpCommand("help", "List of available commands", "h")); commandManager.addCommand(new EndCommand("end", "Stops Apex", "stop", "exit")); commandManager.addCommand(new DebugCommand("debug", "Turns the debug mode on/off", "d")); commandManager.addCommand(new StatsCommand("stats", "Shows live stats", "s", "info")); Header generalHeader = copeConfig.getHeader("general"); Key serverKey = generalHeader.getKey("server"); Key balanceKey = generalHeader.getKey("balance"); Key bossKey = generalHeader.getKey("boss"); Key workerKey = generalHeader.getKey("worker"); Key timeoutKey = generalHeader.getKey("timeout"); Key backlogKey = generalHeader.getKey("backlog"); Key probeKey = generalHeader.getKey("probe"); Key debugKey = generalHeader.getKey("debug"); Key statsKey = generalHeader.getKey("stats"); // Set the log level to debug or info based on the config value changeDebug((Boolean.valueOf(debugKey.next().asString())) ? Level.DEBUG : Level.INFO); List<BackendInfo> backendInfo = copeConfig.getHeader("backend").getKeys().stream().map( backend -> new BackendInfo(backend.getName(), backend.next().asString(), backend.next().asInt())) .collect(Collectors.toList()); logger.debug("Mode: {}", mode); logger.debug("Host: {}", serverKey.next().asString()); logger.debug("Port: {}", serverKey.next().asString()); logger.debug("Balance: {}", balanceKey.next().asString()); logger.debug("Backlog: {}", backlogKey.next().asInt()); logger.debug("Boss: {}", bossKey.next().asInt()); logger.debug("Worker: {}", workerKey.next().asInt()); logger.debug("Stats: {}", statsKey.next().asString()); logger.debug("Probe: {}", probeKey.next().asInt()); logger.debug("Backend: {}", backendInfo.stream().map(BackendInfo::getHost).collect(Collectors.joining(", "))); StrategyType type = StrategyType.valueOf(balanceKey.next().asString()); balancingStrategy = BalancingStrategyFactory.create(type, backendInfo); // Disable the resource leak detector ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED); if (PipelineUtils.isEpoll()) { logger.info("Using high performance epoll event notification mechanism"); } else {//from ww w. j a v a 2 s . co m logger.info("Using normal select/poll event notification mechanism"); } // Check boss thread config value int bossThreads = bossKey.next().asInt(); if (bossThreads < PipelineUtils.DEFAULT_THREADS_THRESHOLD) { bossThreads = PipelineUtils.DEFAULT_BOSS_THREADS; logger.warn("Boss threads needs to be greater or equal than {}. Using default value of {}", PipelineUtils.DEFAULT_THREADS_THRESHOLD, PipelineUtils.DEFAULT_BOSS_THREADS); } // Check worker thread config value int workerThreads = workerKey.next().asInt(); if (workerThreads < PipelineUtils.DEFAULT_THREADS_THRESHOLD) { workerThreads = PipelineUtils.DEFAULT_WORKER_THREADS; logger.warn("Worker threads needs to be greater or equal than {}. Using default value of {}", PipelineUtils.DEFAULT_THREADS_THRESHOLD, PipelineUtils.DEFAULT_WORKER_THREADS); } bossGroup = PipelineUtils.newEventLoopGroup(bossThreads, new ApexThreadFactory("Apex Boss Thread")); workerGroup = PipelineUtils.newEventLoopGroup(workerThreads, new ApexThreadFactory("Apex Worker Thread")); if (statsKey.next().asBoolean()) { // Only measure connections per second if stats are enabled connectionsPerSecondTask = new ConnectionsPerSecondTask(); // Load the total stats long[] totalBytes = FileUtil.loadStats(); logger.debug("Loaded total read bytes: {}", totalBytes[0]); logger.debug("Loaded total written bytes: {}", totalBytes[1]); // Traffic shaping handler with default check interval of one second trafficShapingHandler = new GlobalTrafficShapingHandler(workerGroup, 0, 0); // Set the total stats ReflectionUtil.setAtomicLong(trafficShapingHandler.trafficCounter(), "cumulativeReadBytes", totalBytes[0]); ReflectionUtil.setAtomicLong(trafficShapingHandler.trafficCounter(), "cumulativeWrittenBytes", totalBytes[1]); logger.debug("Traffic stats collect handler initialized"); } try { serverChannel = bootstrap(bossGroup, workerGroup, serverKey.next().asString(), serverKey.next().asInt(), backlogKey.next().asInt(), timeoutKey.next().asInt(), timeoutKey.next().asInt()); int probe = probeKey.next().asInt(); if (probe < -1 || probe == 0) { probe = 10000; logger.warn("Probe time value must be -1 to turn it off or greater than 0"); logger.warn("Using default probe time of 10000 milliseconds (10 seconds)"); } if (probe != -1) { backendTask = (mode == Mode.TCP) ? new CheckSocketBackendTask(balancingStrategy) : new CheckDatagramBackendTask(balancingStrategy); scheduledExecutorService.scheduleAtFixedRate(backendTask, 0, probe, TimeUnit.MILLISECONDS); } else { // Shutdown unnecessary scheduler scheduledExecutorService.shutdown(); } restServer = new RestServer(copeConfig); restServer.start(); logger.info("Apex listening on {}:{}", serverKey.next().asString(), serverKey.next().asInt()); } catch (Exception e) { e.printStackTrace(); } }