java多线程 post_Netty实现java多线程Post请求解析(Map参数类型)—SKY

/*** 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;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值