/*** Created on 2016/7/23.
*
* http请求处理类r
*@author: xiaoyongyong*/
public class HttpServerHandler extendsChannelHandlerAdapter {private static final Log LOG = LogFactory.getLog(HttpServerHandler.class);private static ScheduledExecutorService executor = null;private static volatile BlockingQueue queue = null;private static volatile String serverIp = null;static{
executor=Executors.newScheduledThreadPool(Integer.valueOf(PropertiesUtil.readValue(Constants.SERVER_THREAD_POOL)));
queue= new ArrayBlockingQueue<>(Integer.valueOf(PropertiesUtil.readValue(Constants.SERVER_QUEUE_CAPACITY)));
}
@Overridepublic voidchannelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throwsException {if (serverIp == null) {
serverIp=((InetSocketAddress) ctx.channel().localAddress()).getAddress().getHostAddress();
}
queue.put(newQueueBean(ctx, msg));
}
@Overridepublic voidexceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
LOG.error("ctx close!",cause);
ctx.close();
}classQueueBean {private finalChannelHandlerContext ctx;private finalObject msg;
QueueBean(ChannelHandlerContext ctx, Object msg) {this.ctx =ctx;this.msg =msg;
}publicChannelHandlerContext getCtx() {returnctx;
}publicObject getMsg() {returnmsg;
}
}static{
Thread thread= new Thread(new ChannelReadScan(),"ServerChannelReadScan");
thread.setDaemon(true);
thread.start();
}private static class ChannelReadScan implementsRunnable {
@Overridepublic voidrun() {try{while (true) {final QueueBean queueBean =queue.take();
executor.execute(newRunnable() {
@Overridepublic voidrun() {try{
ChannelHandlerContext ctx=queueBean.getCtx();
Object msg=queueBean.getMsg();if (msg instanceofHttpRequest) {
HttpRequest req=(HttpRequest) msg;if(HttpHeaders.is100ContinueExpected(req)) {
ctx.write(newDefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.CONTINUE));
}boolean keepAlive =HttpHeaders.isKeepAlive(req);//解析http头部
for (Map.Entryh : req.headers()) {
LOG.debug("HEADER: " + h.getKey() + " = " +h.getValue());
}
String uri=req.getUri();
LOG.debug("uri:" +uri);if (uri.endsWith("/favicon.ico")) {return;
}if (uri.startsWith("http")) {
uri= uri.replaceAll("http://[^/]+","");
}
String requestPath= uri.trim().split("\\?")[0];
Map params =convertToMap(uri,req);
Object result=service(requestPath, params,req,ctx);
FullHttpResponse response= newDefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(JSON.toJSONString(result).getBytes()));
response.headers().set(CONTENT_TYPE,"text/html; charset=UTF-8");
response.headers().set(CONTENT_LENGTH, response.content().readableBytes());if (!keepAlive) {
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}else{
response.headers().set(CONNECTION, Values.KEEP_ALIVE);
ctx.writeAndFlush(response);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
});
}
}catch(Exception e) {
e.printStackTrace();
}
}private MapconvertToMap(String uri,HttpRequest req) {
Map params = new HashMap<>();//是GET请求
if(HttpMethod.GET.equals(req.getMethod())) {//解析请求参数
QueryStringDecoder queryStringDecoder = newQueryStringDecoder(uri);
Map> paramMap =queryStringDecoder.parameters();for (Map.Entry>entry : paramMap.entrySet()) {
params.put(entry.getKey(), entry.getValue().get(0));
}
}if(HttpMethod.POST.equals(req.getMethod())) {//是POST请求
HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), req);
List postList =decoder.getBodyHttpDatas();for(InterfaceHttpData data : postList) {if (data.getHttpDataType() ==InterfaceHttpData.HttpDataType.Attribute) {
MemoryAttribute attribute=(MemoryAttribute) data;
params.put(attribute.getName(), attribute.getValue());
}
}
}returnparams;
}private Object service(String requestPath, Mapparams,HttpRequest req,ChannelHandlerContext ctx) {long startTime =System.currentTimeMillis();
Object result;try{
result=Dispatcher.service(requestPath, params);long spentTime = System.currentTimeMillis() -startTime;
log(requestPath, req, ctx, (List) result, spentTime);
}catch(Exception e) {
e.printStackTrace();
result= SyncMonitor.createExceptionResult("服务器异常:" +e.getCause().getMessage());
}returnresult;
}private void log(String requestPath, HttpRequest req, ChannelHandlerContext ctx,List result, longspentTime) {for(SyncMonitor syncMonitor: result){
LogBean logBean= newLogBean();
logBean.setAction(requestPath);
logBean.setIn_param(requestPath);
logBean.setC_ip(getClientIp(req, ctx));
logBean.setS_ip(serverIp);int status =(syncMonitor.getStatus());if (status ==SyncMonitor.STATUS_EXCEPTION) {
logBean.setError_msg(JSON.toJSONString(syncMonitor.getMessage()));
}
logBean.setError_no(status+ "");
logBean.setResult(status+ "");
logBean.setSpent_time(spentTime+ "");
logBean.setLog_type("info");
logBean.setSys_no("trade_data_monitor");
LogUtil.info(logBean);
}
}privateString getClientIp(HttpRequest req,ChannelHandlerContext ctx) {
String clientIP= req.headers().get("X-Forwarded-For");if (clientIP == null) {
InetSocketAddress insocket=(InetSocketAddress) ctx.channel()
.remoteAddress();
clientIP=insocket.getAddress().getHostAddress();
}returnclientIP;
}
}
}