Skip to content

Commit

Permalink
# support cli to config
Browse files Browse the repository at this point in the history
  • Loading branch information
ktdynamic committed Jan 30, 2019
1 parent e956fc5 commit aa245f8
Show file tree
Hide file tree
Showing 4 changed files with 152 additions and 6 deletions.
7 changes: 7 additions & 0 deletions http-server/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<netty.version>4.1.9.Final</netty.version>
<apache.commons.cli>1.4</apache.commons.cli>
<logback.version>1.1.7</logback.version>
</properties>

Expand All @@ -20,6 +21,12 @@
<version>${netty.version}</version>
</dependency>

<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>${apache.commons.cli}</version>
</dependency>

<!-- logback -->
<dependency>
<groupId>ch.qos.logback</groupId>
Expand Down
102 changes: 97 additions & 5 deletions http-server/src/main/java/com/zkdcloud/proxy/http/ServerStart.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.zkdcloud.proxy.http;

import com.zkdcloud.proxy.http.handler.JudgeHttpTypeHandler;
import com.zkdcloud.proxy.http.util.ServerConfigure;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
Expand All @@ -14,9 +15,12 @@
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.apache.commons.cli.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
Expand All @@ -30,12 +34,17 @@ public class ServerStart {
* static logger
*/
private static Logger logger = LoggerFactory.getLogger(ServerStart.class);
private static NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
private static NioEventLoopGroup workGroup = new NioEventLoopGroup(Math.min(Runtime.getRuntime().availableProcessors() + 1, 32),
new DefaultThreadFactory("proxy-workers"));
private static NioEventLoopGroup bossGroup;
private static NioEventLoopGroup workGroup;

public static void main(String[] args) throws InterruptedException {
// init args
initCliArgs(args);
ServerBootstrap serverBootstrap = new ServerBootstrap();
bossGroup = new NioEventLoopGroup(1);
workGroup = new NioEventLoopGroup(serverConfigure.getNumberWorkers(),
new DefaultThreadFactory("proxy-workers"));


serverBootstrap.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
Expand All @@ -44,8 +53,9 @@ public static void main(String[] args) throws InterruptedException {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline()
.addFirst("idle", new IdleStateHandler(0, 0, 7, TimeUnit.MINUTES){
.addFirst("idle", new IdleStateHandler(0, 0, serverConfigure.getSecondsClientIdle(), TimeUnit.SECONDS) {
private Logger logger = LoggerFactory.getLogger("client idle logger");

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
Expand All @@ -59,9 +69,91 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc
.addLast("http-init", new JudgeHttpTypeHandler());
}
});
int port = args != null && args.length >= 1 ? Integer.parseInt(args[0]) : 1081;
short port = serverConfigure.getPort();
logger.info("http server start at : : {}", port);

serverBootstrap.bind(port).sync().channel().closeFuture().sync();
}

public static ServerConfigure serverConfigure = new ServerConfigure();
private static Options OPTIONS = new Options();
private static CommandLine commandLine;
private static String HELP_STRING = null;

/**
* init args
*
* @param args args
*/
private static void initCliArgs(String[] args) {
// validate args
{
CommandLineParser commandLineParser = new DefaultParser();
// help
OPTIONS.addOption("help","usage help");
// port
OPTIONS.addOption(Option.builder("p").hasArg(true).longOpt("port").type(Short.TYPE).desc("the port of server startup").build());
// number fo workers thread
OPTIONS.addOption(Option.builder("n").hasArg(true).longOpt("number_workers").type(Short.TYPE).desc("the number of workers thread").build());
// client idle seconds
OPTIONS.addOption(Option.builder("c").hasArg(true).longOpt("seconds_client_idle").type(Long.TYPE).desc("the seconds of client idle").build());
// remote idle seconds
OPTIONS.addOption(Option.builder("r").hasArg(true).longOpt("seconds_remote_idle").type(Long.TYPE).desc("the seconds of remote idle").build());
try {
commandLine = commandLineParser.parse(OPTIONS, args);
} catch (ParseException e) {
logger.error("{}\n{}", e.getMessage(), getHelpString());
System.exit(0);
}
}

// init serverConfigure
{
if(commandLine.hasOption("help")){
logger.info("\n" + getHelpString());
System.exit(1);
}
// server port
String portOptionValue = commandLine.getOptionValue("p");
short port = portOptionValue == null || "".equals(portOptionValue) ? 1081 : Short.parseShort(portOptionValue);
serverConfigure.setPort(port);

// netty workers thread number(client)
String numberWorksOptionValue = commandLine.getOptionValue("n");
short numberWorks = numberWorksOptionValue == null || "".equals(numberWorksOptionValue) ?
(short) Math.min(Runtime.getRuntime().availableProcessors() + 1, 32) : Short.parseShort(numberWorksOptionValue);
serverConfigure.setNumberWorkers(numberWorks);

// client idle seconds, default is 1 min
String scOptionValue = commandLine.getOptionValue("c");
short secondsClientIdle = scOptionValue == null || "".equals(scOptionValue) ? 60 : Short.parseShort(scOptionValue);
serverConfigure.setSecondsClientIdle(secondsClientIdle);

// remote idle seconds, default is 1min
String srOptionValue = commandLine.getOptionValue("r");
short secondsRemoteIdle = srOptionValue == null || "".equals(srOptionValue) ? 60 : Short.parseShort(srOptionValue);
serverConfigure.setSecondsRemoteIdle(secondsRemoteIdle);
}

}

/**
* get string of help usage
*
* @return help string
*/
private static String getHelpString() {
if (HELP_STRING == null) {
HelpFormatter helpFormatter = new HelpFormatter();

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PrintWriter printWriter = new PrintWriter(byteArrayOutputStream);
helpFormatter.printHelp(printWriter, HelpFormatter.DEFAULT_WIDTH, "http server proxy", null,
OPTIONS, HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD, null);
printWriter.flush();
HELP_STRING = new String(byteArrayOutputStream.toByteArray());
printWriter.close();
}
return HELP_STRING;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.zkdcloud.proxy.http.util;

import com.zkdcloud.proxy.http.ServerStart;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.socket.nio.NioSocketChannel;
Expand All @@ -19,7 +20,7 @@ public static ChannelFuture connect(InetSocketAddress dstAddress, EventLoopGroup
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<Channel>() {
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addFirst("idle", new IdleStateHandler(0, 0, 30, TimeUnit.SECONDS){
ch.pipeline().addFirst("idle", new IdleStateHandler(0, 0, ServerStart.serverConfigure.getSecondsRemoteIdle(), TimeUnit.SECONDS){
private Logger logger = LoggerFactory.getLogger("remote idle logger");
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.zkdcloud.proxy.http.util;

/**
* server config
*
* @author zk
* @since 2019/1/30
*/
public class ServerConfigure {
private short port;
private short numberWorkers;
private long secondsClientIdle;
private long secondsRemoteIdle;

public short getPort() {
return port;
}

public void setPort(short port) {
this.port = port;
}

public short getNumberWorkers() {
return numberWorkers;
}

public void setNumberWorkers(short numberWorkers) {
this.numberWorkers = numberWorkers;
}

public long getSecondsClientIdle() {
return secondsClientIdle;
}

public void setSecondsClientIdle(long secondsClientIdle) {
this.secondsClientIdle = secondsClientIdle;
}

public long getSecondsRemoteIdle() {
return secondsRemoteIdle;
}

public void setSecondsRemoteIdle(long secondsRemoteIdle) {
this.secondsRemoteIdle = secondsRemoteIdle;
}
}

0 comments on commit aa245f8

Please sign in to comment.