本文整理汇总了Java中com.ning.http.client.AsyncHttpClient类的典型用法代码示例。如果您正苦于以下问题:Java AsyncHttpClient类的具体用法?Java AsyncHttpClient怎么用?Java AsyncHttpClient使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
AsyncHttpClient类属于com.ning.http.client包,在下文中一共展示了AsyncHttpClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testJobSidelining_ShouldSidelineJobsAfter404s
import com.ning.http.client.AsyncHttpClient; //导入依赖的package包/类
@Test
public void testJobSidelining_ShouldSidelineJobsAfter404s() throws Exception {
/* Creating legit job */
AsyncHttpClient.BoundRequestBuilder request = asyncHttpClient.preparePost("http://localhost:11000/jobs/scheduled").setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
request.setBody(objectMapper.writeValueAsString(JobApiUtil.createTestScheduledJob("testJob1", "http://localhost:11000/test", TestConstants.ONE_SECOND)));
final ListenableFuture<Response> futureResponse = request.execute();
final Response response = futureResponse.get();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_OK);
/* Creating Job that is destined to be sidelined*/
AsyncHttpClient.BoundRequestBuilder request2 = asyncHttpClient.preparePost("http://localhost:11000/jobs/scheduled").setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
request2.setBody(objectMapper.writeValueAsString(JobApiUtil.createTestScheduledJob("testJob2", "http://localhost:11000/test/404", TestConstants.ONE_SECOND)));
final ListenableFuture<Response> futureResponseForRequest2 = request2.execute();
final Response response2 = futureResponseForRequest2.get();
assertThat(response2.getStatusCode()).isEqualTo(HttpStatus.SC_OK);
Thread.sleep(5 * TestConstants.ONE_SECOND + 100l);
testApiCounter.assertHeard("test", 5); // Legit job executed 5 times in 5 seconds
testApiCounter.assertHeard("test404", 3); // Doomed job executed just thrice
final Iterable<Job> allJobs = repository.findAll();
assertThat(allJobs).extracting(Job::getName).containsExactly("testJob1","testJob2");
assertThat(allJobs).extracting("sideLined",Boolean.class).containsExactly(false,true);
}
示例2: AsyncHttpClientHelper
import com.ning.http.client.AsyncHttpClient; //导入依赖的package包/类
/**
* Constructor that gives you maximum control over configuration and behavior.
*
* @param builder
* The builder that will create the {@link #asyncHttpClient} and execute all the async downstream HTTP
* requests.
* @param performSubSpanAroundDownstreamCalls
* Pass in true to have a distributed tracing subspan added to each downstream call to measure the time spent
* on the downstream call, false if you do not want subspans performed. The subspans can be used to determine
* how much time is spent processing in your app vs. waiting for downstream requests.
*/
public AsyncHttpClientHelper(AsyncHttpClientConfig.Builder builder, boolean performSubSpanAroundDownstreamCalls) {
this.performSubSpanAroundDownstreamCalls = performSubSpanAroundDownstreamCalls;
Map<String, String> mdcContextMap = MDC.getCopyOfContextMap();
Deque<Span> distributedTraceStack = null;
try {
// We have to unlink tracing and MDC from the current thread before we setup the async http client library,
// otherwise all the internal threads it uses to do its job will be attached to the current thread's
// trace/MDC info forever and always.
distributedTraceStack = Tracer.getInstance().unregisterFromThread();
MDC.clear();
AsyncHttpClientConfig cf = builder.build();
asyncHttpClient = new AsyncHttpClient(cf);
}
finally {
// Reattach the original tracing and MDC before we leave
if (mdcContextMap == null)
MDC.clear();
else
MDC.setContextMap(mdcContextMap);
Tracer.getInstance().registerWithThread(distributedTraceStack);
}
}
示例3: doHttpLog
import com.ning.http.client.AsyncHttpClient; //导入依赖的package包/类
protected static void doHttpLog(String baseDomain, AsyncHttpClient httpClient, long viewerId, String metric,
String referrer, String url, String location, String productId, String videoId, String uuid, long orderId) {
String logUrl = baseDomain + buildLogQueryString(metric, uuid, viewerId,location, referrer, url, productId, videoId, orderId);
if(debug){
if(metric.equals(ORDER)){
System.out.println("====> ORDER "+logUrl);
} else if(metric.equals(CLICK)){
System.out.println("==> CLICK "+logUrl);
} else {
System.out.println("=> PAGEVIEW "+logUrl);
}
}
httpClient.prepareGet(logUrl).execute();
}
示例4: main
import com.ning.http.client.AsyncHttpClient; //导入依赖的package包/类
public static void main(String[] args) throws IOException {
initHttpClientPool();
for (int i = 0; i < 100; i++) {
try {
String url = "https://log.rfxlab.com/ping";
AsyncHttpClient ramdomAsyncHttpClient = getRamdomAsyncHttpClient();
String ua = ramdomAsyncHttpClient.getConfig().getUserAgent();
Future<Response> f = ramdomAsyncHttpClient.prepareGet(url).execute();
Response r = f.get();
System.out.println(ua + " => " +r.getResponseBody());
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("done");
shutdownAllHttpClientPools();
}
示例5: newNettyAsyncHttpClient
import com.ning.http.client.AsyncHttpClient; //导入依赖的package包/类
public static AsyncHttpClient newNettyAsyncHttpClient(final int timeout, final PoolConfig poolConfig) {
final NettyConnectionsPool pool = new NettyConnectionsPool( //
poolConfig.getMaxTotalConnections(), //
poolConfig.getMaxNrConnectionsPerHost(), //
poolConfig.getMaxIdleTime(), //
poolConfig.getMaxConnectionLifetime(), //
false, //
new HashedWheelTimer());
final AsyncHttpClientConfig config =
new AsyncHttpClientConfig.Builder().setConnectionTimeoutInMs(timeout) //
.setRequestTimeoutInMs(timeout) //
.setMaximumConnectionsPerHost(poolConfig.getMaxNrConnectionsPerHost()) //
.setConnectionsPool(pool) //
.build();
return new AsyncHttpClient(config);
}
示例6: testUnsidelining_ShouldUnsidelineGivenJob_AndRunAsPerSchedule
import com.ning.http.client.AsyncHttpClient; //导入依赖的package包/类
@Test
public void testUnsidelining_ShouldUnsidelineGivenJob_AndRunAsPerSchedule() throws Exception {
/* Creating Job that is destined to be sidelined*/
AsyncHttpClient.BoundRequestBuilder request = asyncHttpClient.preparePost("http://localhost:11000/jobs/scheduled").setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
request.setBody(objectMapper.writeValueAsString(JobApiUtil.createTestScheduledJob("testJob2", "http://localhost:11000/test/404", TestConstants.ONE_SECOND)));
final ListenableFuture<Response> futureResponseForRequest = request.execute();
final Response response = futureResponseForRequest.get();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_OK);
Thread.sleep(4 * TestConstants.ONE_SECOND + 100l);
testApiCounter.assertHeard("test404", 3); // Doomed job executed just thrice
final List<Job> allJobs = repository.findAll();
assertThat(allJobs).extracting("sideLined", Boolean.class).containsExactly(true); // asserting job is sidelined
AsyncHttpClient.BoundRequestBuilder requestUnSideline = asyncHttpClient.preparePut("http://localhost:11000/jobs/testJob2/unsideline").setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
final ListenableFuture<Response> unsidelineResponse = requestUnSideline.execute();
assertThat(unsidelineResponse.get().getStatusCode()).isEqualTo(HttpStatus.SC_OK);
assertThat((repository.findByName("testJob2").isSidelined())).isFalse(); // This check should happen within 3 seconds of the job being unsidelined. Mostly we are good
}
示例7: waitForNumQueuesToBePresent
import com.ning.http.client.AsyncHttpClient; //导入依赖的package包/类
public static void waitForNumQueuesToBePresent(int numQueues, AsyncHttpClient httpClient, String rabbitAdminPort) throws Exception {
for (int i = 1; i <= CONNECTION_MAX_ATTEMPT; i++) {
try {
List<String> queueNames = getQueueNames(httpClient, rabbitAdminPort);
if (queueNames.size()==numQueues) {
log.infoWithParams("Correct number of queues found.", "numQueues", queueNames.size(), "expected", numQueues, "names", queueNames);
break;
}else{
log.infoWithParams("Wrong number of queues found.", "numQueues", queueNames.size(), "expected", numQueues, "names", queueNames);
Thread.sleep(CONNECTION_BACKOFF_TIME);
}
} catch (Exception ignored) {
log.infoWithParams("Failed to create connection.. will try again ", "attempt", i, "max-attempts", CONNECTION_MAX_ATTEMPT);
Thread.sleep(CONNECTION_BACKOFF_TIME);
if (i == CONNECTION_MAX_ATTEMPT) {
throw ignored;
}
}
}
}
示例8: setup
import com.ning.http.client.AsyncHttpClient; //导入依赖的package包/类
@Before
public void setup() throws Exception {
dockerContainers.rabbit().assertUp();
rabbitTcpPort = dockerContainers.rabbit().tcpPort();
rabbitAdminPort = dockerContainers.rabbit().adminPort();
log.infoWithParams("****** Rabbit broker is up and running *****");
BrokerAddresses addresses = new BrokerAddresses("amqp://localhost:" + rabbitTcpPort);
channelFactory = new DefaultChannelFactory(addresses, connectionSettings);
consumerFactory = new DefaultConsumerFactory(channelFactory, consumeSettings);
publisherFactory = new DefaultPublisherFactory(channelFactory, publishSettings);
httpClient = new AsyncHttpClient();
messagesSeen.clear();
createQueues(channelFactory, inputQueue, new Exchange(inputExchange));
publisher = publisherFactory.createPublisher();
RxJavaHooks.setOnIOScheduler(null);
}
示例9: setup
import com.ning.http.client.AsyncHttpClient; //导入依赖的package包/类
@Before
public void setup() throws Exception {
dockerContainers.resetAll(false);
dockerContainers.rabbit(RABBIT_1).assertUp();
dockerContainers.rabbit(RABBIT_2).assertUp();
String rabbitTcpPort = dockerContainers.rabbit(RABBIT_1).tcpPort();
rabbitAdminPort = dockerContainers.rabbit(RABBIT_1).adminPort();
String rabbit2TcpPort = dockerContainers.rabbit(RABBIT_2).tcpPort();
log.infoWithParams("****** Rabbit brokers are up and running *****");
BrokerAddresses addresses = new BrokerAddresses(
"amqp://localhost:" + rabbitTcpPort + "," +
"amqp://localhost:" + rabbit2TcpPort
);
channelFactory = new DefaultChannelFactory(addresses, connectionSettings);
consumerFactory = new DefaultConsumerFactory(channelFactory, consumeSettings);
DefaultPublisherFactory publisherFactory = new DefaultPublisherFactory(channelFactory, publishSettings);
httpClient = new AsyncHttpClient();
messagesSeen.clear();
createQueues(channelFactory, inputQueue, new Exchange(inputExchange));
publisher = publisherFactory.createPublisher();
}
示例10: getAsyncRequestBuilder
import com.ning.http.client.AsyncHttpClient; //导入依赖的package包/类
private AsyncHttpClient.BoundRequestBuilder getAsyncRequestBuilder(AsyncHttpClient client, Map<String, String> queryString, String... paths) {
String target = config.getServerName();
if (config.getServerPort() != 80) {
target = target + ":" + config.getServerPort();
}
for (String path : paths) {
target += path;
}
AsyncHttpClient.BoundRequestBuilder requestBuilder = client.preparePost(target);
for (String key : queryString.keySet()) {
requestBuilder.addQueryParameter(key, queryString.get(key));
}
requestBuilder.addHeader(HTTP_HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON);
return requestBuilder;
}
示例11: HttpWorker
import com.ning.http.client.AsyncHttpClient; //导入依赖的package包/类
/**
* Instantiates a new http worker.
*
* @param actorMaxOperationTimeoutSec the actor max operation timeout sec
* @param client the client
* @param requestUrl the request url
* @param httpMethod the http method
* @param postData the post data
* @param httpHeaderMap the http header map
* @param responseHeaderMeta the response header meta
*/
public HttpWorker(final int actorMaxOperationTimeoutSec,
final AsyncHttpClient client, final String requestUrl,
final HttpMethod httpMethod, final String postData,
final Map<String, String> httpHeaderMap,
final ResponseHeaderMeta responseHeaderMeta
) {
this.actorMaxOperationTimeoutSec = actorMaxOperationTimeoutSec;
this.client = client;
this.requestUrl = requestUrl;
this.httpMethod = httpMethod;
this.postData = postData;
if (httpHeaderMap != null)
this.httpHeaderMap.putAll(httpHeaderMap);
this.responseHeaderMeta = responseHeaderMeta;
}
示例12: OperationWorker
import com.ning.http.client.AsyncHttpClient; //导入依赖的package包/类
/**
* Instantiates a new operation worker.
*
* @param request
* the request
* @param client
* the client
* @param httpPollerProcessor
* the http poller processor
*/
public OperationWorker(final TaskRequest request,
final AsyncHttpClient client,
final HttpPollerProcessor httpPollerProcessor) {
super();
this.client = client;
this.request = request;
/**
* 20130917: change to add uniform target node capability
*/
this.trueTargetNode = (request.getHostUniform() == null) ? request
.getHost() : request.getHostUniform();
// if needs poller; init
if (request.isPollable()) {
pollerData = new PollerData();
this.httpPollerProcessor = httpPollerProcessor;
logger.info("Request is Pollable: poller info: "
+ httpPollerProcessor.toString());
}
}
示例13: MiosUnitConnector
import com.ning.http.client.AsyncHttpClient; //导入依赖的package包/类
/**
* @param unit
* The host to connect to. Give a reachable hostname or IP address, without protocol or port
*/
public MiosUnitConnector(MiosUnit unit, MiosBinding binding) {
logger.debug("Constructor: unit '{}', binding '{}'", unit, binding);
this.unit = unit;
this.binding = binding;
Builder builder = new AsyncHttpClientConfig.Builder();
builder.setRequestTimeoutInMs(unit.getTimeout());
// Use the JDK Provider for now, we're not looking for server-level
// scalability, and we'd like to lighten the load for folks wanting to
// run atop RPi units.
this.client = new AsyncHttpClient(new JDKAsyncHttpProvider(builder.build()));
pollCall = new LongPoll();
pollThread = new Thread(pollCall);
}
示例14: shouldParseParams
import com.ning.http.client.AsyncHttpClient; //导入依赖的package包/类
@Test
public void shouldParseParams() throws Exception {
// Given
final ProviderClient providerClient = new ProviderClient(mock(PactConfiguration.class), mock(AsyncHttpClient.class));
final String queryString = "q=someValue&some=otherValue";
final Request request = mock(Request.class);
final Option option = mock(Option.class);
when(request.query()).thenReturn(option);
when(option.isEmpty()).thenReturn(false);
when(option.get()).thenReturn(queryString);
// When
final List<Param> params = providerClient.parseParams(request);
// Then
assertThat(params.size(), is(2));
assertThat(params.get(0), is(new Param("q", "someValue")));
assertThat(params.get(1), is(new Param("some", "otherValue")));
}
示例15: shouldNotFailWithoutParams
import com.ning.http.client.AsyncHttpClient; //导入依赖的package包/类
@Test
public void shouldNotFailWithoutParams() throws Exception {
// Given
final ProviderClient providerClient = new ProviderClient(mock(PactConfiguration.class), mock(AsyncHttpClient.class));
final Request request = mock(Request.class);
final Option option = mock(Option.class);
when(request.query()).thenReturn(option);
when(option.isEmpty()).thenReturn(true);
// When
final List<Param> params = providerClient.parseParams(request);
// Then
assertThat(params, is(empty()));
}