基于cglib 反射 netty http1.0
程序员文章站
2022-05-28 19:13:22
...
数据源 代码位置:http://knight-black-bob.iteye.com/blog/2256698
netty 代码位置:http://knight-black-bob.iteye.com/blog/2256690
package com.netty.dto; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class ResponceInfo { private Integer code; private String message; private Object data; public ResponceInfo() { } public ResponceInfo(Integer code, String message, Object data) { this.code = code; this.message = message; this.data = data; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } @Override public String toString() { Gson gson=new GsonBuilder() .disableHtmlEscaping() .serializeNulls() .create();; return gson.toJson(this); } }
package com.netty.business; import org.springframework.cglib.reflect.FastClass; import org.springframework.cglib.reflect.FastMethod; import com.netty.dto.ResponceInfo; public class CGLibCode { public static ResponceInfo execute(Object targetObject,String methodName,Class<?>[] parameterTypes, Object[] parameters){ try { FastClass serviceFastClass = FastClass.create(targetObject.getClass()); FastMethod serviceFastMethod = serviceFastClass.getMethod(methodName, parameterTypes); return (ResponceInfo)serviceFastMethod.invoke(targetObject, parameters); } catch (Exception e) { return null ; } } }
package com.netty.business; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.log4j.Logger; import org.springframework.util.StringUtils; import com.common.util.ParamsUtils; import com.google.common.base.Strings; import com.netty.service.NettyServicePool; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.QueryStringDecoder; import io.netty.handler.codec.http.multipart.Attribute; import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory; import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder; import io.netty.handler.codec.http.multipart.InterfaceHttpData; import io.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType; public class BusinessHandler { private static Logger logger = Logger.getLogger(BusinessHandler.class); private static HttpRequest req; public BusinessHandler(){ req = null; } public static HttpRequest getReq() { return req; } public static void setReq(HttpRequest req) { BusinessHandler.req = req; } public BusinessHandler(HttpRequest req) { BusinessHandler.req = req; } public String handler(){ Map<String, List<String>> _params=null; String srcUrl = req.getUri(); try { if(req.getMethod()==HttpMethod.GET) _params=_getParams(srcUrl); else _params=_postParams(srcUrl); } catch (Exception e) {} return _execute(_params); } private static String _execute(Map<String, List<String>> params) { String cln=ParamsUtils.getStringFromMap(params, "cln");//接口名 String mod=ParamsUtils.getStringFromMap(params, "mod");//方法名 if(StringUtils.hasText(cln) && StringUtils.hasText(mod)){ Object autoService= NettyServicePool.NETTYSERVICES.get(cln); if(null!=autoService){ params.remove("cln"); params.remove("mod"); String[] ps=new String[params.size()]; Class<?>[] cs=new Class<?>[params.size()]; int i=0; for (Entry<String, List<String>> e : params.entrySet()) { cs[i]=String.class; String _value=null ; if(null!=e.getValue() && e.getValue().size()>0) _value=e.getValue().get(0); ps[i]=_value; i++; } return CGLibCode.execute(autoService, mod, cs, ps).toString(); } } return null; } private static Map<String, List<String>> _postParams(String srcUrl) throws IOException { HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), req); Map<String, List<String>> params=new HashMap<String, List<String>>(); if (decoder != null) { List<InterfaceHttpData> postDatas = decoder.getBodyHttpDatas(); for (InterfaceHttpData postData:postDatas) { if (postData.getHttpDataType() == HttpDataType.Attribute){ Attribute attribute = (Attribute) postData; String v=attribute.getValue(); List<String> list=new ArrayList<String>(); list.add(Strings.nullToEmpty(v)); params.put(attribute.getName(), list); } } } return params; } //未加密 private static Map<String, List<String>> _getParams(String srcUrl) { QueryStringDecoder decoder = new QueryStringDecoder(srcUrl); Map<String, List<String>> params=new HashMap<String, List<String>>(); params = decoder.parameters(); return params; } }
package com.netty.core; import org.apache.log4j.Logger; import com.netty.business.BusinessHandler; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.HttpHeaders.Names; public class NettyServerHandler extends ChannelInboundHandlerAdapter { Logger logger = Logger.getLogger(NettyServerHandler.class); @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { logger.info("channelRead " + msg); if (msg instanceof HttpRequest){ HttpRequest req = (HttpRequest) msg; logger.info(req.getUri()); if(HttpHeaders.is100ContinueExpected(req)){ ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); } String _result=new BusinessHandler(req).handler(); logger.info("_result : " + _result); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(_result.getBytes())); response.headers().set(Names.CONTENT_TYPE, "text/html; charset=utf-8"); response.headers().set(Names.CONTENT_LENGTH, response.content().readableBytes()); ctx.write(response).addListener(ChannelFutureListener.CLOSE); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.info("exceptionCaught "); ctx.close(); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { logger.info("channelReadComplete "); ctx.flush(); } }
package test.netty; import java.net.URI; import org.junit.Test; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequestEncoder; import io.netty.handler.codec.http.HttpResponseDecoder; import io.netty.handler.codec.http.HttpVersion; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpResponse; public class NettyClient2Test { public void connect(String host, int port) throws Exception { EventLoopGroup workerGroup = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码 ch.pipeline().addLast(new HttpResponseDecoder()); // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码 ch.pipeline().addLast(new HttpRequestEncoder()); ch.pipeline().addLast(new HttpClientInboundHandler2()); } }); // Start the client. ChannelFuture f = b.connect(host, port).sync(); URI uri = new URI("http://127.0.0.1:8443?cln=mifiDeviceService&mod=getMifiDeviceById&id="+6); String msg = "cln=mifiDeviceService&mod=getMifiDeviceById&id=6"; DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes("UTF-8"))); // 构建http请求 request.headers().set(HttpHeaders.Names.HOST, host); request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes()); // 发送http请求 f.channel().write(request); f.channel().flush(); // f.channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); } } @Test public void Test(){ try{ NettyClient2Test client = new NettyClient2Test(); client.connect("127.0.0.1", 8443); }catch(Exception e){ e.printStackTrace(); } } } class HttpClientInboundHandler2 extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; System.out.println("CONTENT_TYPE:" + response.headers().get(HttpHeaders.Names.CONTENT_TYPE)); } if(msg instanceof HttpContent) { HttpContent content = (HttpContent)msg; ByteBuf buf = content.content(); System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8)); buf.release(); } } }
package com.mifi.serviceimpl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.common.util.netty.StatusCode; import com.mifi.bean.MifiDevice; import com.mifi.dao.MifiDeviceDao; import com.mifi.service.MifiDeviceService; import com.netty.dto.ResponceInfo; import com.netty.service.NettyServerService; @NettyServerService(name="mifiDeviceService") @Service public class MifiDeviceServiceImpl implements MifiDeviceService { @Autowired MifiDeviceDao dao; // 1 true 0, false public ResponceInfo hasMifiDeviceById(String id){ //return dao.getMifiDeviceById(id) == null ? false : true ; int result=0; if(dao.getMifiDeviceById(Long.parseLong(id)) != null) result=1; return new ResponceInfo(StatusCode.STATUS_SUCCCESS,StatusCode.MSG_SUCCESS,result); } public ResponceInfo getMifiDeviceById(String id){ MifiDevice mifiDevice = null; try{ mifiDevice = dao.getMifiDeviceById(Long.parseLong(id)); }catch(Exception e){ } return new ResponceInfo(StatusCode.STATUS_SUCCCESS,StatusCode.MSG_SUCCESS,mifiDevice); } public ResponceInfo findAllMifiDevices(){ List<MifiDevice> mlist = null ; try{ mlist= dao.findAllMifiDevices(); }catch(Exception e){ } return new ResponceInfo(StatusCode.STATUS_SUCCCESS,StatusCode.MSG_SUCCESS,mlist); } public ResponceInfo addMifiDevice(MifiDevice mifiDevice){ int result=0; try{ result=1; dao.addMifiDevice(mifiDevice); }catch(Exception e){ } return new ResponceInfo(StatusCode.STATUS_SUCCCESS,StatusCode.MSG_SUCCESS,result); } public ResponceInfo delMifiDeviceById(String id){ int result=0; try{ result=1; dao.delMifiDeviceById(Long.parseLong(id)); }catch(Exception e){ } return new ResponceInfo(StatusCode.STATUS_SUCCCESS,StatusCode.MSG_SUCCESS,result); } public ResponceInfo updateMifiDevice(MifiDevice mifiDevice){ int result=0; try{ result=1; dao.updateMifiDevice(mifiDevice); }catch(Exception e){ } return new ResponceInfo(StatusCode.STATUS_SUCCCESS,StatusCode.MSG_SUCCESS,result); } }
捐助开发者
在兴趣的驱动下,写一个免费
的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。
谢谢您的赞助,我会做的更好!