使用Netty构建APP后台服务器实现http请求

APP通过Http请求后台服务器的关键是连接url,及返回参数。

在开发APP的过程中,会频繁的与后台服务器进行交互,当业务比较复杂的情况下,后台服务接口开发速度不见得会满足APP的调用,经过APP调用后台服务进行分析得出,可以通过设置url及返回数据两个参数进行后台服务器的配置。按照一定的配置规则,先模拟一个能够让APP能够跑起来的后台服务,实现APP的快速开发。

后台实现代码如下:

// 后台服务器代码,监听指定端口提供HTTP请求调用服务

public class AppServerMonitor implements Runnable {
private int port;
public AppServerMonitor(int port){
this.port = port;
}

public void run() {
// TODO Auto-generated method stub
EventLoopGroup acceptorGroup = new NioEventLoopGroup();  
       EventLoopGroup clientGroup = new NioEventLoopGroup();  
       try {  
           ServerBootstrap serverBookstrap = new ServerBootstrap();  
           serverBookstrap.group(acceptorGroup, clientGroup).channel(NioServerSocketChannel.class)  
           .option(ChannelOption.SO_BACKLOG, 100)  
           .childHandler(new ChannelInitializer<SocketChannel>(){  
               protected void initChannel(SocketChannel sc) throws Exception {  
                   sc.pipeline().addLast("http-decoder",new HttpRequestDecoder());  
                   sc.pipeline().addLast("http-aggregator",new HttpObjectAggregator(64*1024));  
                   sc.pipeline().addLast("http-encoder",new HttpResponseEncoder());  
                   sc.pipeline().addLast("http-handler",new UrlHandler());  
               }  
           });  
           ChannelFuture channelFuture = serverBookstrap.bind(port).sync();  
           channelFuture.channel().closeFuture().sync();  
       } catch (InterruptedException e) {
e.printStackTrace();
} finally {  
           acceptorGroup.shutdownGracefully();  
           clientGroup.shutdownGracefully();  
       }  
}

public static void main(String[] args){
// url数据模拟器 可以从数据库进行配置 配置
ResponseMap.setResponse("/abcd", "{\"aa\":\"abcde\"}");
ResponseMap.setResponse("/dcba", "{\"aa\":\"dcba\"}");


// 

String url = "****";

String values="******";

ResponseMap.setResponse(url , values}");

new AppServerMonitor(8080).run();
}
}


// netty解码器

public class UrlHandler extends SimpleChannelInboundHandler<FullHttpRequest> {


@Override
protected void messageReceived(ChannelHandlerContext ctx,
FullHttpRequest req) throws Exception {
// TODO Auto-generated method stub
//解码不成功  
        if(!req.getDecoderResult().isSuccess())  
        {  
            sendErrorToClient(ctx,HttpResponseStatus.BAD_REQUEST);  
            return ;  
        }  
        if(req.getMethod().compareTo(HttpMethod.GET)!=0){  
            sendErrorToClient(ctx,HttpResponseStatus.METHOD_NOT_ALLOWED);  
            return;  
        }  
        String uri=req.getUri();  
        String value = ResponseMap.getResponse(uri);
        sendValuesClient(ctx,value);
}

    private void sendValuesClient(ChannelHandlerContext ctx, String value) throws Exception {  
        ByteBuf buffer=Unpooled.copiedBuffer(value.getBytes());  
        FullHttpResponse resp=new DefaultFullHttpResponse(HTTP_1_1,HttpResponseStatus.OK,buffer);  
        MimetypesFileTypeMap mimeTypeMap=new MimetypesFileTypeMap();  
        resp.headers().set("CONTENT-TYPE", "UTF-8");  
        ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);  
    }  



    public static final HttpVersion HTTP_1_1 = new HttpVersion("HTTP", 1, 1, true); 
    private static final String CRLF = "\r\n";  
    
private void sendErrorToClient(ChannelHandlerContext ctx,
HttpResponseStatus status) throws UnsupportedEncodingException {
ByteBuf buffer=Unpooled.copiedBuffer(("系统服务出错:"+status.toString()+CRLF).getBytes("utf-8"));  
         FullHttpResponse resp=new DefaultFullHttpResponse(HTTP_1_1,status,buffer);  
         resp.headers().set("Content-Type", "text/html;charset=utf-8");  
         ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);  
}

}


// 连接,返回值容器自定义一个静态Map用于存储

public class ResponseMap {
private static Map<String, String>  responseMap = new HashMap<String, String>();
public static void setResponse(String url, String value){
responseMap.put(url, value);
}
/**
* 默认返回
* @param url
* @return
*/
public static String getResponse(String url){
String value = responseMap.get(url);
if (null == value){
value = "{success:0}";
}
return value;
}
}


//对于静态MAP 也可以使用数据库进行url + values 存储


// maven 配置

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>5.0.0.Alpha1</version>
</dependency>


// 实现效果如下: 





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值