热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

基于netty的异步http请求

packagecom.pt.utils;importio.netty.bootstrap.Bootstrap;importio.netty.channel.ChannelFuture;imp

 

 

package com.pt.utils;

import io.netty.bootstrap.Bootstrap;
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.*;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;

import java.net.URI;
import java.util.Map;

/**
*
@author panteng
* @description
* @date 17-3-20.
*/
public class NonBlockHttpClient {
public static EventLoopGroup workerGroup = new NioEventLoopGroup(1);
public static Bootstrap b = new Bootstrap();
public static final EventExecutorGroup executor = new DefaultEventExecutorGroup(2);
static {
b.group(workerGroup);
b.channel(NioSocketChannel.
class);
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
1000);
}
public static Object lock = new Object();
/**
* 异步GET请求
*
*
@param url
*
@param head
*
@param handler
*
@return
*/
public static Boolean get(String url, Map head, final HttpHandler handler) {
try {
URI uri
= new URI(url);
String domain
= uri.getHost();
Integer port
= uri.getPort() <0 ? 80 : uri.getPort();
DefaultFullHttpRequest request
= new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());
if (head == null) {
request.headers().add(
"Host", domain);
request.headers().add(
"User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0");
request.headers().add(
"Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
request.headers().add(
"Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
request.headers().add(
"Connection", "keep-alive");
request.headers().add(
"Cache-Control", "max-age=0");
}
else {
for (Map.Entry entry : head.entrySet()) {
request.headers().add((String) entry.getKey(), entry.getValue());
}
}
ChannelInitializer channelInitializer
= new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
// 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
socketChannel.pipeline().addLast(new HttpResponseDecoder());
// 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
socketChannel.pipeline().addLast(new HttpRequestEncoder());
socketChannel.pipeline().addLast(executor,
new GeneralHandler(handler));
}
};
ChannelFuture f;
synchronized (lock) {
b.handler(channelInitializer);
f
= b.connect(domain, port).sync();
}
f.channel().writeAndFlush(request);
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static void close() {
try {
executor.shutdownGracefully();
workerGroup.shutdownGracefully();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
核心类1

 

package com.pt.utils;

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;

import java.util.HashMap;
import java.util.Map;

/**
*
@author panteng
* @description
* @date 17-3-20.
*/
public class GeneralHandler extends ChannelInboundHandlerAdapter {
com.pt.utils.HttpHandler httpHandler;
Integer respLength
= Integer.MAX_VALUE; // 响应报文长度
Map head = new HashMap();
String respContent
= "";

public GeneralHandler(com.pt.utils.HttpHandler handler) {
this.httpHandler = handler;
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof HttpResponse) {
HttpResponse response
= (HttpResponse) msg;
for (Map.Entry entry : response.headers().entries()) {
head.put((String) entry.getKey(), (String) entry.getValue());
}
if (response.headers().get("Content-Length") != null) {
respLength
= Integer.parseInt(response.headers().get("Content-Length"));
}
}

if (msg instanceof HttpContent) {
HttpContent content
= (HttpContent) msg;
ByteBuf buf
= content.content();
respContent
+= buf.toString(httpHandler.getCharset());
((HttpContent) msg).release();
if (respContent.getBytes().length >= respLength || !buf.isReadable()) {
ctx.channel().close();
httpHandler.handler(head, respContent);
}
}
}
}
核心类2

 

package com.pt.utils;

import java.nio.charset.Charset;
import java.util.Map;

/**
*
@author panteng
* @description http响应的异步回调
* @date 17-3-20.
*/
public interface HttpHandler {
public void handler(Map headMap, String body);
public Charset getCharset();
}
用户自定义处理接口

 

使用用例:

package com.pt.utils.test;

import com.pt.utils.HttpHandler;

import java.nio.charset.Charset;
import java.util.Map;

/**
*
@author panteng
* @description
* @date 17-3-20.
*/
public class MyHandler implements HttpHandler {
boolean isFinish = false;
String id;

public MyHandler(String id) {
this.id = id;
}

public void handler(Map headMap, String body) {
try {
Thread.sleep(
3000);
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println(id
+ "自己处理:" + body);
this.setIsFinish(true);
}

public Charset getCharset() {
return Charset.forName("UTF-8");
}

public boolean isFinish() {
return isFinish;
}

public void setIsFinish(boolean isFinish) {
this.isFinish = isFinish;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}
}
用户定义处理的实现

 

package com.pt.utils.test;

import com.pt.utils.NonBlockHttpClient;

/**
*
@author panteng
* @description
* @date 17-3-22.
*/
public class NonBlockHttpClientTest {
public static void main(String[] arges) {
MyHandler myHandler
= new MyHandler("A");
MyHandler myHandler1
= new MyHandler("B");
MyHandler myHandler2
= new MyHandler("C");
MyHandler myHandler3
= new MyHandler("D");
NonBlockHttpClient
.get(url1,
null, myHandler);
NonBlockHttpClient
.get(url2,
null, myHandler1);
NonBlockHttpClient
.get(url3,
null, myHandler2);
NonBlockHttpClient
.get(url4,
null, myHandler3);
System.out.println(
"做别的事情");
try {
Thread.sleep(
2000);
}
catch (Exception e) {
e.printStackTrace();
}
while (!(myHandler.isFinish() && myHandler1.isFinish() && myHandler2.isFinish() && myHandler3.isFinish())) {
try {
Thread.sleep(
10);
}
catch (Exception e) {
e.printStackTrace();
}
}
NonBlockHttpClient.close();
System.out.println(
"退出主函数... ...");
}
}

 


推荐阅读
  • 本文介绍如何使用阿里云的fastjson库解析包含时间戳、IP地址和参数等信息的JSON格式文本,并进行数据处理和保存。 ... [详细]
  • 使用 Azure Service Principal 和 Microsoft Graph API 获取 AAD 用户列表
    本文介绍了一段通用代码示例,该代码不仅能够操作 Azure Active Directory (AAD),还可以通过 Azure Service Principal 的授权访问和管理 Azure 订阅资源。Azure 的架构可以分为两个层级:AAD 和 Subscription。 ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • 本文介绍了Java并发库中的阻塞队列(BlockingQueue)及其典型应用场景。通过具体实例,展示了如何利用LinkedBlockingQueue实现线程间高效、安全的数据传递,并结合线程池和原子类优化性能。 ... [详细]
  • 深入解析Spring Cloud Ribbon负载均衡机制
    本文详细介绍了Spring Cloud中的Ribbon组件如何实现服务调用的负载均衡。通过分析其工作原理、源码结构及配置方式,帮助读者理解Ribbon在分布式系统中的重要作用。 ... [详细]
  • 本文深入探讨了 Java 中的 Serializable 接口,解释了其实现机制、用途及注意事项,帮助开发者更好地理解和使用序列化功能。 ... [详细]
  • 本文详细介绍了Java编程语言中的核心概念和常见面试问题,包括集合类、数据结构、线程处理、Java虚拟机(JVM)、HTTP协议以及Git操作等方面的内容。通过深入分析每个主题,帮助读者更好地理解Java的关键特性和最佳实践。 ... [详细]
  • 本文介绍了如何通过 Maven 依赖引入 SQLiteJDBC 和 HikariCP 包,从而在 Java 应用中高效地连接和操作 SQLite 数据库。文章提供了详细的代码示例,并解释了每个步骤的实现细节。 ... [详细]
  • 本文提供了使用Java实现Bellman-Ford算法解决POJ 3259问题的代码示例,详细解释了如何通过该算法检测负权环来判断时间旅行的可能性。 ... [详细]
  • 本文详细探讨了JDBC(Java数据库连接)的内部机制,重点分析其作为服务提供者接口(SPI)框架的应用。通过类图和代码示例,展示了JDBC如何注册驱动程序、建立数据库连接以及执行SQL查询的过程。 ... [详细]
  • 深入解析JVM垃圾收集器
    本文基于《深入理解Java虚拟机:JVM高级特性与最佳实践》第二版,详细探讨了JVM中不同类型的垃圾收集器及其工作原理。通过介绍各种垃圾收集器的特性和应用场景,帮助读者更好地理解和优化JVM内存管理。 ... [详细]
  • 前言--页数多了以后需要指定到某一页(只做了功能,样式没有细调)html ... [详细]
  • 本文详细介绍了Akka中的BackoffSupervisor机制,探讨其在处理持久化失败和Actor重启时的应用。通过具体示例,展示了如何配置和使用BackoffSupervisor以实现更细粒度的异常处理。 ... [详细]
  • 将Web服务部署到Tomcat
    本文介绍了如何在JDeveloper 12c中创建一个Java项目,并将其打包为Web服务,然后部署到Tomcat服务器。内容涵盖从项目创建、编写Web服务代码、配置相关XML文件到最终的本地部署和验证。 ... [详细]
author-avatar
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有