Java Code Examples for com.linecorp.armeria.client.endpoint.EndpointGroup#of()

The following examples show how to use com.linecorp.armeria.client.endpoint.EndpointGroup#of() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ArmeriaCallFactoryTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void respectsHttpClientUri_endpointGroup() throws Exception {
    final EndpointGroup group = EndpointGroup.of(Endpoint.of("127.0.0.1", server.httpPort()),
                                                 Endpoint.of("127.0.0.1", server.httpPort()));

    final Service service = ArmeriaRetrofit.builder("http", group)
                                           .addConverterFactory(converterFactory)
                                           .build()
                                           .create(Service.class);

    try (ClientRequestContextCaptor ctxCaptor = Clients.newContextCaptor()) {
        final Response<Pojo> response = service.postForm("Cony", 26).get();

        final RequestLog log = ctxCaptor.get().log().whenComplete().join();
        assertThat(log.sessionProtocol()).isSameAs(SessionProtocol.H2C);
        assertThat(log.requestHeaders().authority()).isEqualTo("127.0.0.1:" + server.httpPort());

        // TODO(ide) Use the actual `host:port`. See https://github.com/line/armeria/issues/379
        final HttpUrl url = response.raw().request().url();
        assertThat(url.scheme()).isEqualTo("http");
        assertThat(url.host()).startsWith("armeria-group-");
        assertThat(url.pathSegments()).containsExactly("postForm");
    }
}
 
Example 2
Source File: ArmeriaCallFactoryTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void urlAnnotation() throws Exception {
    final EndpointGroup groupFoo = EndpointGroup.of(Endpoint.of("127.0.0.1", 1),
                                                    Endpoint.of("127.0.0.1", 1));
    final EndpointGroup groupBar = EndpointGroup.of(Endpoint.of("127.0.0.1", server.httpPort()),
                                                    Endpoint.of("127.0.0.1", server.httpPort()));

    final WebClient baseWebClient = WebClient.builder(SessionProtocol.HTTP, groupFoo)
                                             .endpointRemapper(endpoint -> {
                                                 if ("group_bar".equals(endpoint.host())) {
                                                     return groupBar;
                                                 } else {
                                                     return endpoint;
                                                 }
                                             })
                                             .build();

    final Service service = ArmeriaRetrofit.builder(baseWebClient)
                                           .addConverterFactory(converterFactory)
                                           .build()
                                           .create(Service.class);

    // The request should never go to 'groupFoo'.
    final Pojo pojo = service.fullUrl("http://group_bar/pojo").get();
    assertThat(pojo).isEqualTo(new Pojo("Cony", 26));
}
 
Example 3
Source File: DefaultWebClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void endpointRemapper() {
    final EndpointGroup group = EndpointGroup.of(Endpoint.of("127.0.0.1", 1),
                                                 Endpoint.of("127.0.0.1", 1));
    final WebClient client = WebClient.builder("http://group")
                                      .endpointRemapper(endpoint -> {
                                          if ("group".equals(endpoint.host())) {
                                              return group;
                                          } else {
                                              return endpoint;
                                          }
                                      })
                                      .build();

    try (ClientRequestContextCaptor ctxCaptor = Clients.newContextCaptor()) {
        client.get("/").aggregate();
        final ClientRequestContext cctx = ctxCaptor.get();
        await().untilAsserted(() -> {
            assertThat(cctx.endpointGroup()).isSameAs(group);
            assertThat(cctx.endpoint()).isEqualTo(Endpoint.of("127.0.0.1", 1));
            assertThat(cctx.request().authority()).isEqualTo("127.0.0.1:1");
        });
    }
}
 
Example 4
Source File: DefaultWebClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void endpointRemapperForUnspecifiedUri() {
    final EndpointGroup group = EndpointGroup.of(Endpoint.of("127.0.0.1", 1),
                                                 Endpoint.of("127.0.0.1", 1));
    final WebClient client = WebClient.builder()
                                      .endpointRemapper(endpoint -> {
                                          if ("group".equals(endpoint.host())) {
                                              return group;
                                          } else {
                                              return endpoint;
                                          }
                                      })
                                      .build();

    try (ClientRequestContextCaptor ctxCaptor = Clients.newContextCaptor()) {
        client.get("http://group").aggregate();
        final ClientRequestContext cctx = ctxCaptor.get();
        await().untilAsserted(() -> {
            assertThat(cctx.endpointGroup()).isSameAs(group);
            assertThat(cctx.endpoint()).isEqualTo(Endpoint.of("127.0.0.1", 1));
            assertThat(cctx.request().authority()).isEqualTo("127.0.0.1:1");
        });
    }
}
 
Example 5
Source File: RetryingClientWithMetricsTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void retryingThenMetricCollectingWithConnectionRefused() throws Exception {
    // The first request will fail with an UnprocessedException and
    // the second request will succeed with 200.
    final EndpointGroup group = EndpointGroup.of(Endpoint.of("127.0.0.1", 1),
                                                 server.httpEndpoint());
    final WebClient client =
            WebClient.builder(SessionProtocol.HTTP, group)
                     .factory(clientFactory)
                     .decorator(MetricCollectingClient.newDecorator(meterIdPrefixFunction))
                     .decorator(RetryingClient.newDecorator(RetryRule.onUnprocessed()))
                     .build();
    assertThat(client.get("/ok").aggregate().join().status()).isEqualTo(HttpStatus.OK);

    // wait until 2 calls are recorded.
    await().untilAsserted(() -> {
        assertThat(MoreMeters.measureAll(meterRegistry))
                .containsEntry("foo.requests#count{http.status=200,method=GET,result=success}", 1.0)
                .containsEntry("foo.requests#count{http.status=200,method=GET,result=failure}", 0.0)
                .containsEntry("foo.requests#count{http.status=0,method=GET,result=success}", 0.0)
                .containsEntry("foo.requests#count{http.status=0,method=GET,result=failure}", 1.0);
    });
}
 
Example 6
Source File: RetryingClientWithMetricsTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void metricCollectingThenRetryingWithConnectionRefused() throws Exception {
    // The first request will fail with an UnprocessedException and
    // the second request will succeed with 200.
    final EndpointGroup group = EndpointGroup.of(Endpoint.of("127.0.0.1", 1),
                                                 server.httpEndpoint());
    final WebClient client =
            WebClient.builder(SessionProtocol.HTTP, group)
                     .factory(clientFactory)
                     .decorator(RetryingClient.newDecorator(RetryRule.onUnprocessed()))
                     .decorator(MetricCollectingClient.newDecorator(MeterIdPrefixFunction.ofDefault("foo")))
                     .build();

    assertThat(client.get("/ok").aggregate().join().status()).isEqualTo(HttpStatus.OK);

    // wait until 1 call is recorded.
    await().untilAsserted(() -> {
        assertThat(MoreMeters.measureAll(meterRegistry))
                .containsEntry("foo.requests#count{http.status=200,method=GET,result=success}", 1.0)
                .containsEntry("foo.requests#count{http.status=200,method=GET,result=failure}", 0.0);
    });
}
 
Example 7
Source File: ArmeriaRetrofitBuilderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void build_armeriaGroupAuthority() {
    final Endpoint endpoint = Endpoint.of("127.0.0.1", 8080);
    final EndpointGroup group = EndpointGroup.of(endpoint, endpoint);

    assertThat(ArmeriaRetrofit.of(SessionProtocol.H2C, endpoint).baseUrl().toString())
            .isEqualTo("http://127.0.0.1:8080/");

    assertThat(ArmeriaRetrofit.of(SessionProtocol.H2, group).baseUrl().toString())
            .startsWith("https://armeria-group-");
}
 
Example 8
Source File: ArmeriaCallFactoryTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void urlAnnotation_uriWithoutScheme() throws Exception {
    final EndpointGroup group = EndpointGroup.of(Endpoint.of("127.0.0.1", server.httpPort()),
                                                 Endpoint.of("127.0.0.1", server.httpPort()));

    final WebClient baseWebClient = WebClient.builder("http://127.0.0.1:1")
                                             .endpointRemapper(endpoint -> {
                                                 if ("my-group".equals(endpoint.host())) {
                                                     return group;
                                                 } else {
                                                     return endpoint;
                                                 }
                                             })
                                             .build();

    final Service service = ArmeriaRetrofit.builder(baseWebClient)
                                           .addConverterFactory(converterFactory)
                                           .build()
                                           .create(Service.class);

    assertThat(service.fullUrl("//localhost:" + server.httpPort() + "/nest/pojo").get()).isEqualTo(
            new Pojo("Leonard", 21));
    assertThat(service.fullUrl("//my-group/nest/pojo").get()).isEqualTo(new Pojo("Leonard", 21));

    assertThat(service.fullUrl("//localhost:" + server.httpPort() + "/pojo").get()).isEqualTo(
            new Pojo("Cony", 26));
    assertThat(service.fullUrl("//my-group/pojo").get()).isEqualTo(new Pojo("Cony", 26));
}
 
Example 9
Source File: RetryingClientAuthorityHeaderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static WebClient newHttpClientWithEndpointGroup() {
    final EndpointGroup endpointGroup = EndpointGroup.of(
            Endpoint.of("www.foo.com", backend1.httpPort()).withIpAddr("127.0.0.1"),
            Endpoint.of("www.bar.com", backend2.httpPort()).withIpAddr("127.0.0.1"));

    return WebClient.builder(SessionProtocol.H2C, endpointGroup)
                    .decorator(RetryingClient.newDecorator(
                            RetryRule.builder().onServerErrorStatus().onException().thenBackoff()))
                    .build();
}
 
Example 10
Source File: WeightedRoundRobinStrategyBenchmark.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static EndpointGroup getEndpointGroup(List<Endpoint> endpoints) {
    return EndpointGroup.of(EndpointSelectionStrategy.weightedRoundRobin(), endpoints);
}
 
Example 11
Source File: StaticEndpointGroupIntegrationTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
public void testRoundRobinServerGroup() throws Exception {
    serverOne.start();
    serverTwo.start();
    serverThree.start();

    final EndpointGroup endpointGroup = EndpointGroup.of(
            Endpoint.of("127.0.0.1", serverOne.httpPort()).withWeight(1),
            Endpoint.of("127.0.0.1", serverTwo.httpPort()).withWeight(2),
            Endpoint.of("127.0.0.1", serverThree.httpPort()).withWeight(3));

    HelloService.Iface ipService = Clients.newClient("ttext+http", endpointGroup, "/serverIp",
                                                     HelloService.Iface.class);
    assertThat(ipService.hello("ip")).isEqualTo(
            "host:127.0.0.1:" + serverOne.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo(
            "host:127.0.0.1:" + serverTwo.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverThree.httpPort());

    final EndpointGroup serverGroup2 = EndpointGroup.of(
            Endpoint.of("127.0.0.1", serverOne.httpPort()).withWeight(2),
            Endpoint.of("127.0.0.1", serverTwo.httpPort()).withWeight(4),
            Endpoint.of("127.0.0.1", serverThree.httpPort()).withWeight(3));

    ipService = Clients.newClient("tbinary+http", serverGroup2, "/serverIp",
                                  HelloService.Iface.class);

    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverOne.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverThree.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverTwo.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverOne.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverThree.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverTwo.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverThree.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverTwo.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverTwo.httpPort());

    //new round
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverOne.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverThree.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverTwo.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverOne.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverThree.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverTwo.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverThree.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverTwo.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverTwo.httpPort());

    //direct connect to ip host
    ipService = Clients.newClient("tbinary+http://127.0.0.1:" + serverOne.httpPort() + "/serverIp",
                                  HelloService.Iface.class);
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverOne.httpPort());
    assertThat(ipService.hello("ip")).isEqualTo("host:127.0.0.1:" + serverOne.httpPort());
}
 
Example 12
Source File: HttpClientIntegrationTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void testResolvedEndpointWithAlternateAuthority() throws Exception {
    final EndpointGroup group = EndpointGroup.of(Endpoint.of("localhost", server.httpPort())
                                                         .withIpAddr("127.0.0.1"));
    testEndpointWithAlternateAuthority(group);
}
 
Example 13
Source File: HttpClientIntegrationTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void testUnresolvedEndpointWithAlternateAuthority() throws Exception {
    final EndpointGroup group = EndpointGroup.of(Endpoint.of("localhost", server.httpPort()));
    testEndpointWithAlternateAuthority(group);
}
 
Example 14
Source File: RetryingClientLoadBalancingTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Makes sure that {@link RetryingClient} respects the {@link Endpoint} selection order.
 */
@ParameterizedTest
@EnumSource(TestMode.class)
void test(TestMode mode) {
    server.start();
    final List<Integer> expectedPorts = server.server().activePorts().keySet().stream()
                                              .map(InetSocketAddress::getPort)
                                              .collect(toImmutableList());

    final EndpointGroup group = EndpointGroup.of(EndpointSelectionStrategy.roundRobin(),
                                                 expectedPorts.stream()
                                                              .map(port -> Endpoint.of("127.0.0.1", port))
                                                              .collect(toImmutableList()));

    final RetryRule retryRule = (ctx, cause) -> {
        // Get the response status.
        final HttpStatus status;
        if (ctx.log().isAvailable(RequestLogProperty.RESPONSE_HEADERS)) {
            status = ctx.log().partial().responseHeaders().status();
        } else {
            status = null;
        }

        // Retry only once on failure.
        if (!HttpStatus.OK.equals(status) && AbstractRetryingClient.getTotalAttempts(ctx) <= 1) {
            return CompletableFuture.completedFuture(RetryDecision.retry(Backoff.withoutDelay()));
        } else {
            return CompletableFuture.completedFuture(RetryDecision.noRetry());
        }
    };
    final WebClient c = WebClient.builder(SessionProtocol.H2C, group)
                                 .decorator(RetryingClient.builder(retryRule)
                                                          .newDecorator())
                                 .build();

    for (int i = 0; i < NUM_PORTS; i++) {
        c.get(mode.path).aggregate().join();
    }

    switch (mode) {
        case SUCCESS:
            assertThat(accessedPorts).isEqualTo(expectedPorts);
            break;
        case FAILURE:
            final List<Integer> expectedPortsWhenRetried =
                    ImmutableList.<Integer>builder()
                            .addAll(expectedPorts)
                            .addAll(expectedPorts)
                            .build();
            assertThat(accessedPorts).isEqualTo(expectedPortsWhenRetried);
            break;
    }
}
 
Example 15
Source File: HealthCheckedEndpointGroupBuilderTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@BeforeEach
void beforeEach() {
    delegate = EndpointGroup.of(Endpoint.of("endpoint1"));
}