当前位置: 首页>>代码示例>>Java>>正文


Java DefaultAsyncHttpClient类代码示例

本文整理汇总了Java中org.asynchttpclient.DefaultAsyncHttpClient的典型用法代码示例。如果您正苦于以下问题:Java DefaultAsyncHttpClient类的具体用法?Java DefaultAsyncHttpClient怎么用?Java DefaultAsyncHttpClient使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


DefaultAsyncHttpClient类属于org.asynchttpclient包,在下文中一共展示了DefaultAsyncHttpClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: DRPCQueryResultPubscriber

import org.asynchttpclient.DefaultAsyncHttpClient; //导入依赖的package包/类
/**
 * Create an instance from a given {@link BulletConfig}. Requires {@link DRPCConfig#DRPC_HTTP_CONNECT_TIMEOUT_MS},
 * {@link DRPCConfig#DRPC_HTTP_CONNECT_RETRY_LIMIT}, {@link DRPCConfig#DRPC_SERVERS}, {@link DRPCConfig#DRPC_HTTP_PORT},
 * and {@link DRPCConfig#DRPC_HTTP_PATH} to be set. To be used in PubSub.Context#QUERY_SUBMISSION mode.
 *
 * @param config A non-null config that contains the required settings.
 */
public DRPCQueryResultPubscriber(BulletConfig config) {
    Objects.requireNonNull(config);

    Number connectTimeout = config.getRequiredConfigAs(DRPCConfig.DRPC_HTTP_CONNECT_TIMEOUT_MS, Number.class);
    Number retryLimit = config.getRequiredConfigAs(DRPCConfig.DRPC_HTTP_CONNECT_RETRY_LIMIT, Number.class);
    List<String> servers = (List<String>) config.getRequiredConfigAs(DRPCConfig.DRPC_SERVERS, List.class);
    String protocol = config.getRequiredConfigAs(DRPCConfig.DRPC_HTTP_PROTOCOL, String.class);
    String port = config.getRequiredConfigAs(DRPCConfig.DRPC_HTTP_PORT, String.class);
    String path = config.getRequiredConfigAs(DRPCConfig.DRPC_HTTP_PATH, String.class);
    String function = config.getRequiredConfigAs(DRPCConfig.DRPC_FUNCTION, String.class);

    List<String> endpoints = servers.stream()
                                    .map(url -> String.format(URL_TEMPLATE, protocol, url, port, path, function))
                                    .collect(Collectors.toList());
    this.urls = new RandomPool<>(endpoints);
    AsyncHttpClientConfig clientConfig = new DefaultAsyncHttpClientConfig.Builder()
                                                .setConnectTimeout(connectTimeout.intValue())
                                                .setMaxRequestRetry(retryLimit.intValue())
                                                .setReadTimeout(NO_TIMEOUT)
                                                .setRequestTimeout(NO_TIMEOUT)
                                                .build();
    // This is thread safe
    client = new DefaultAsyncHttpClient(clientConfig);
    responses = new ConcurrentLinkedQueue<>();
}
 
开发者ID:yahoo,项目名称:bullet-storm,代码行数:33,代码来源:DRPCQueryResultPubscriber.java

示例2: markDimensionCacheHealthy

import org.asynchttpclient.DefaultAsyncHttpClient; //导入依赖的package包/类
/**
 * Makes the dimensions passthrough.
 * <p>
 * This method sends a lastUpdated date to each dimension in the dimension cache, allowing the health checks
 * to pass without having to set up a proper dimension loader. For each dimension, d, the following query is
 * sent to the /v1/cache/dimensions/d endpoint:
 * {
 *     "name": "d",
 *     "lastUpdated": "2016-01-01"
 * }
 *
 * @param port  The port through which we access the webservice
 *
 * @throws IOException If something goes terribly wrong when building the JSON or sending it
 */
private static void markDimensionCacheHealthy(int port) throws IOException {
    AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
    for (DimensionConfig dimensionConfig : new WikiDimensions().getAllDimensionConfigurations()) {
        String dimension = dimensionConfig.getApiName();
        BoundRequestBuilder boundRequestBuilder = asyncHttpClient.preparePost("http://localhost:" + port +
                "/v1/cache/dimensions/" + dimension)
                .addHeader("Content-type", "application/json")
                .setBody(
                        String.format("{\n \"name\":\"%s\",\n \"lastUpdated\":\"2016-01-01\"\n}", dimension)
                );

        ListenableFuture<Response> responseFuture = boundRequestBuilder.execute();
        try {
            Response response = responseFuture.get();
            LOG.debug("Mark Dimension Cache Updated Response: ", response);
        } catch (InterruptedException | ExecutionException e) {
            LOG.warn("Failed while marking dimensions healthy", e);
        }
    }
}
 
开发者ID:yahoo,项目名称:fili,代码行数:36,代码来源:WikiMain.java

示例3: initializeWebClient

import org.asynchttpclient.DefaultAsyncHttpClient; //导入依赖的package包/类
/**
 * Initialize the client config.
 *
 * @param requestTimeout  Timeout to use for the client configuration.
 *
 * @return the set up client
 */
private static AsyncHttpClient initializeWebClient(int requestTimeout) {

    LOG.debug("Druid request timeout: {}ms", requestTimeout);

    // Build the configuration
    AsyncHttpClientConfig config = new DefaultAsyncHttpClientConfig.Builder()
            .setReadTimeout(requestTimeout)
            .setRequestTimeout(requestTimeout)
            .setConnectTimeout(requestTimeout)
            .setConnectionTtl(requestTimeout)
            .setPooledConnectionIdleTimeout(requestTimeout)
            .setFollowRedirect(true)
            .build();

    return new DefaultAsyncHttpClient(config);
}
 
开发者ID:yahoo,项目名称:fili,代码行数:24,代码来源:AsyncDruidWebServiceImpl.java

示例4: shouldDoNothingIfNoServersAreSet

import org.asynchttpclient.DefaultAsyncHttpClient; //导入依赖的package包/类
@Test
public void shouldDoNothingIfNoServersAreSet() throws Exception {
    // given
    TestPropertyValues
            .of("edison.serviceregistry.enabled=true")
            .and("edison.serviceregistry.servers=")
            .applyTo(context);
    context.register(DefaultAsyncHttpClient.class);
    context.register(ApplicationInfoConfiguration.class);
    context.register(AsyncHttpRegistryClient.class);
    context.refresh();

    RegistryClient bean = context.getBean(RegistryClient.class);

    assertThat(bean.isRunning(), is(false));
}
 
开发者ID:otto-de,项目名称:edison-microservice,代码行数:17,代码来源:AsyncHttpRegistryClientTest.java

示例5: shouldDoNothingIfNoServiceAreSet

import org.asynchttpclient.DefaultAsyncHttpClient; //导入依赖的package包/类
@Test
public void shouldDoNothingIfNoServiceAreSet() throws Exception {
    // given
    TestPropertyValues
            .of("edison.serviceregistry.enabled=true")
            .and("edison.serviceregistry.service=")
            .applyTo(context);
    context.register(DefaultAsyncHttpClient.class);
    context.register(ApplicationInfoConfiguration.class);
    context.register(AsyncHttpRegistryClient.class);
    context.refresh();

    RegistryClient bean = context.getBean(RegistryClient.class);

    assertThat(bean.isRunning(), is(false));
}
 
开发者ID:otto-de,项目名称:edison-microservice,代码行数:17,代码来源:AsyncHttpRegistryClientTest.java

示例6: shouldDoNothingIfRegistryDisabled

import org.asynchttpclient.DefaultAsyncHttpClient; //导入依赖的package包/类
@Test
public void shouldDoNothingIfRegistryDisabled() throws Exception {
    // given
    TestPropertyValues
            .of("edison.serviceregistry.enabled=false")
            .and("edison.serviceregistry.servers=http://foo")
            .and("edison.serviceregistry.service=http://test")
            .applyTo(context);
    context.register(DefaultAsyncHttpClient.class);
    context.register(ApplicationInfoConfiguration.class);
    context.register(AsyncHttpRegistryClient.class);
    context.refresh();

    RegistryClient bean = context.getBean(RegistryClient.class);

    assertThat(bean.isRunning(), is(false));
}
 
开发者ID:otto-de,项目名称:edison-microservice,代码行数:18,代码来源:AsyncHttpRegistryClientTest.java

示例7: testAcceptWebSocket

import org.asynchttpclient.DefaultAsyncHttpClient; //导入依赖的package包/类
@Test
public void testAcceptWebSocket() {
    TestServer server = testServer(19001);
    running(server, () -> {
        try {
            AsyncHttpClientConfig config = new DefaultAsyncHttpClientConfig.Builder().setMaxRequestRetry(0).build();
            AsyncHttpClient client = new DefaultAsyncHttpClient(config);
            WebSocketClient webSocketClient = new WebSocketClient(client);

            try {
                String serverURL = "ws://localhost:19001/ws";
                WebSocketClient.LoggingListener listener = new WebSocketClient.LoggingListener();
                CompletableFuture<WebSocket> completionStage = webSocketClient.call(serverURL, listener);

                await().until(() -> {
                    assertThat(completionStage).isDone();
                });
            } finally {
                //noinspection ThrowFromFinallyBlock
                client.close();
            }
        } catch (Exception e) {
            fail("Unexpected exception", e);
        }
    });
}
 
开发者ID:play2-maven-plugin,项目名称:play2-maven-test-projects,代码行数:27,代码来源:FunctionalTest.java

示例8: getProjectByCloneCodeViaHttp

import org.asynchttpclient.DefaultAsyncHttpClient; //导入依赖的package包/类
@Test
public void getProjectByCloneCodeViaHttp() throws Exception {
    clientPair.appClient.send("getCloneCode 1");
    String token = clientPair.appClient.getBody();
    assertNotNull(token);
    assertEquals(32, token.length());

    AsyncHttpClient httpclient = new DefaultAsyncHttpClient(
            new DefaultAsyncHttpClientConfig.Builder()
                    .setUserAgent(null)
                    .setKeepAlive(true)
                    .build()
    );

    Future<Response> f = httpclient.prepareGet("http://localhost:" + httpPort + "/" + token + "/clone").execute();
    Response response = f.get();
    assertEquals(200, response.getStatusCode());
    String responseBody = response.getResponseBody();
    assertNotNull(responseBody);
    DashBoard dashBoard = JsonParser.parseDashboard(responseBody);
    assertEquals("My Dashboard", dashBoard.name);
}
 
开发者ID:blynkkk,项目名称:blynk-server,代码行数:23,代码来源:CloneWorkFlowTest.java

示例9: init

import org.asynchttpclient.DefaultAsyncHttpClient; //导入依赖的package包/类
@Before
public void init() throws Exception {
    httpServer = new HttpAPIServer(holder).start();
    hardwareServer = new HardwareServer(holder).start();
    appServer = new AppServer(holder).start();
    httpServerUrl = String.format("http://localhost:%s/", httpPort);

    httpclient = new DefaultAsyncHttpClient(
            new DefaultAsyncHttpClientConfig.Builder()
                    .setUserAgent("")
                    .setKeepAlive(true)
                    .build());

    if (clientPair == null) {
        clientPair = initAppAndHardPair(tcpAppPort, tcpHardPort, properties);
    }
    clientPair.hardwareClient.reset();
    clientPair.appClient.reset();
}
 
开发者ID:blynkkk,项目名称:blynk-server,代码行数:20,代码来源:MultiAppTest.java

示例10: init

import org.asynchttpclient.DefaultAsyncHttpClient; //导入依赖的package包/类
@BeforeClass
public static void init() throws Exception {
    properties.setProperty("data.folder", getRelativeDataFolder("/profiles"));
    localHolder = new Holder(properties,
            new MailProperties(Collections.emptyMap()),
            new SmsProperties(Collections.emptyMap()),
            new GCMProperties(Collections.emptyMap()),
            false
    );
    httpServer = new HttpAPIServer(localHolder).start();
    httpsServerUrl = String.format("http://localhost:%s/", httpPort);
    httpclient = new DefaultAsyncHttpClient(
            new DefaultAsyncHttpClientConfig.Builder()
                    .setUserAgent(null)
                    .setKeepAlive(true)
                    .build()
    );
}
 
开发者ID:blynkkk,项目名称:blynk-server,代码行数:19,代码来源:HttpAPIMetricsTest.java

示例11: testAsyncHttpClient

import org.asynchttpclient.DefaultAsyncHttpClient; //导入依赖的package包/类
@Test
public void testAsyncHttpClient() throws Exception {

    final List<String> messages = new ArrayList<>();
    final CountDownLatch latch = new CountDownLatch(1);

    WebSocketTextListener listener = new DefaultWebSocketListener() {
        @Override
        public void onMessage(String message) {
            System.out.println("onMessage: " + message);
            messages.add(message);
            latch.countDown();
        }
    };

    try (AsyncHttpClient client = new DefaultAsyncHttpClient()) {
        WebSocketUpgradeHandler handler = new WebSocketUpgradeHandler.Builder().addWebSocketListener(listener).build();
        WebSocket websocket = client.prepareGet("ws://" + WEBSOCKET_ENDPOINT).execute(handler).get();
        websocket.sendMessage("Kermit");

        Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));
        Assert.assertEquals("Hello Kermit", messages.get(0));
    }
}
 
开发者ID:wildfly-extras,项目名称:wildfly-camel,代码行数:25,代码来源:AhcWSIntegrationTest.java

示例12: Zendesk

import org.asynchttpclient.DefaultAsyncHttpClient; //导入依赖的package包/类
private Zendesk(AsyncHttpClient client, String url, String username, String password) {
    this.logger = LoggerFactory.getLogger(Zendesk.class);
    this.closeClient = client == null;
    this.oauthToken = null;
    this.client = client == null ? new DefaultAsyncHttpClient() : client;
    this.url = url.endsWith("/") ? url + "api/v2" : url + "/api/v2";
    if (username != null) {
        this.realm = new Realm.Builder(username, password)
                .setScheme(Realm.AuthScheme.BASIC)
                .setUsePreemptiveAuth(true)
                .build();
    } else {
        if (password != null) {
            throw new IllegalStateException("Cannot specify token or password without specifying username");
        }
        this.realm = null;
    }
    this.mapper = createMapper();
}
 
开发者ID:cloudbees,项目名称:zendesk-java-client,代码行数:20,代码来源:Zendesk.java

示例13: getHttpClient

import org.asynchttpclient.DefaultAsyncHttpClient; //导入依赖的package包/类
/**
 * Gets an asynchronous {@link HttpClient} to be used by the {@link BlockingSphereClient}.
 * Client is created during first invocation and then cached.
 *
 * @return {@link HttpClient}
 */
private static synchronized HttpClient getHttpClient() {
    if (httpClient == null) {
        final AsyncHttpClient asyncHttpClient =
            new DefaultAsyncHttpClient(
                new DefaultAsyncHttpClientConfig.Builder().setAcceptAnyCertificate(true)
                                                          .setHandshakeTimeout((int) DEFAULT_TIMEOUT)
                                                          .build());
        httpClient = AsyncHttpClientAdapter.of(asyncHttpClient);
    }
    return httpClient;
}
 
开发者ID:commercetools,项目名称:commercetools-sync-java,代码行数:18,代码来源:ClientConfigurationUtils.java

示例14: callbackAnswer

import org.asynchttpclient.DefaultAsyncHttpClient; //导入依赖的package包/类
@RequestMapping(value="/self", produces = { "application/json", "text/json" })
public InstagramUser callbackAnswer() throws IOException, ExecutionException, InterruptedException {
    String uriToCall = INSTAGRAM_USER_ENDPOINT + SELF_SUFFIX+
            ACCESS_TOKEN_SUFFIX + CallbackUrl.getAccessToken();
    AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
    Future<Response> f = asyncHttpClient.prepareGet(uriToCall).execute();
    Response r = f.get();
    InstagramUser instagramUser = objectMapper.readValue(r.getResponseBody(), InstagramUser.class);
    return instagramUser;
}
 
开发者ID:danielyinanc,项目名称:instagram-oauth2,代码行数:11,代码来源:UserCall.java

示例15: getHttpClient

import org.asynchttpclient.DefaultAsyncHttpClient; //导入依赖的package包/类
private AsyncHttpClient getHttpClient(String version) {
    DefaultAsyncHttpClientConfig.Builder confBuilder = new DefaultAsyncHttpClientConfig.Builder();
    confBuilder.setFollowRedirect(true);
    confBuilder.setUserAgent(version);
    confBuilder.setKeepAliveStrategy(new DefaultKeepAliveStrategy() {
        @Override
        public boolean keepAlive(Request ahcRequest, HttpRequest request, HttpResponse response) {
            // Close connection upon a server error or per HTTP spec
            return (response.getStatus().code() / 100 != 5) && super.keepAlive(ahcRequest, request, response);
        }
    });
    AsyncHttpClientConfig config = confBuilder.build();
    return new DefaultAsyncHttpClient(config);
}
 
开发者ID:apache,项目名称:incubator-pulsar,代码行数:15,代码来源:BrokerServiceLookupTest.java


注:本文中的org.asynchttpclient.DefaultAsyncHttpClient类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。