com.linecorp.armeria.client.Endpoint Java Examples
The following examples show how to use
com.linecorp.armeria.client.Endpoint.
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: CuratorDiscoverySpecBuilder.java From armeria with Apache License 2.0 | 6 votes |
private Function<? super ServiceInstance<?>, Endpoint> converter() { if (converter != null) { return converter; } return instance -> { if (!instance.isEnabled()) { return null; } if (instanceId != null && !instanceId.equals(instance.getId())) { return null; } if (useSsl != null && useSsl && instance.getSslPort() != null) { return Endpoint.of(instance.getAddress(), instance.getSslPort()); } if (instance.getPort() != null) { return Endpoint.of(instance.getAddress(), instance.getPort()); } return Endpoint.of(instance.getAddress()); }; }
Example #2
Source File: RequestContextExportingAppenderTest.java From armeria with Apache License 2.0 | 6 votes |
private static ClientRequestContext newClientContext( String path, @Nullable String query) throws Exception { final InetSocketAddress remoteAddress = new InetSocketAddress( InetAddress.getByAddress("server.com", new byte[] { 1, 2, 3, 4 }), 8080); final InetSocketAddress localAddress = new InetSocketAddress( InetAddress.getByAddress("client.com", new byte[] { 5, 6, 7, 8 }), 5678); final String pathAndQuery = path + (query != null ? '?' + query : ""); final HttpRequest req = HttpRequest.of(RequestHeaders.of(HttpMethod.GET, pathAndQuery, HttpHeaderNames.AUTHORITY, "server.com:8080", HttpHeaderNames.USER_AGENT, "some-client")); final ClientRequestContext ctx = ClientRequestContext.builder(req) .remoteAddress(remoteAddress) .localAddress(localAddress) .endpoint(Endpoint.of("server.com", 8080)) .sslSession(newSslSession()) .build(); ctx.setAttr(MY_ATTR, new CustomObject("some-name", "some-value")); return ctx; }
Example #3
Source File: PropertiesEndpointGroupBuilder.java From armeria with Apache License 2.0 | 6 votes |
private static List<Endpoint> loadEndpoints(Properties properties, String endpointKeyPrefix, int defaultPort) { if (!endpointKeyPrefix.endsWith(".")) { endpointKeyPrefix += "."; } final List<Endpoint> newEndpoints = new ArrayList<>(); for (Entry<Object, Object> e : properties.entrySet()) { final String key = (String) e.getKey(); final String value = (String) e.getValue(); if (key.startsWith(endpointKeyPrefix)) { final Endpoint endpoint = Endpoint.parse(value); newEndpoints.add(defaultPort == 0 ? endpoint : endpoint.withDefaultPort(defaultPort)); } } return ImmutableList.copyOf(newEndpoints); }
Example #4
Source File: DnsServiceEndpointGroupTest.java From armeria with Apache License 2.0 | 6 votes |
@Test public void srv() throws Exception { try (TestDnsServer server = new TestDnsServer(ImmutableMap.of( new DefaultDnsQuestion("foo.com.", SRV), new DefaultDnsResponse(0).addRecord(ANSWER, newSrvRecord("foo.com.", 1, 2, "a.foo.com.")) .addRecord(ANSWER, newSrvRecord("foo.com.", 3, 4, "b.foo.com.")) .addRecord(ANSWER, newSrvRecord("unrelated.com.", 0, 0, "asdf.com.")) .addRecord(ANSWER, newTooShortSrvRecord("foo.com.")) .addRecord(ANSWER, newBadNameSrvRecord("foo.com.")) ))) { try (DnsServiceEndpointGroup group = DnsServiceEndpointGroup.builder("foo.com") .serverAddresses(server.addr()) .build()) { assertThat(group.whenReady().get()).containsExactly( Endpoint.of("a.foo.com", 2).withWeight(1), Endpoint.of("b.foo.com", 4).withWeight(3)); } } }
Example #5
Source File: HealthCheckedEndpointGroupLongPollingPingTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void noPingAtAll() throws Exception { final BlockingQueue<RequestLogAccess> healthCheckRequestLogs = new LinkedTransferQueue<>(); this.healthCheckRequestLogs = healthCheckRequestLogs; final Endpoint endpoint = Endpoint.of("127.0.0.1", server.httpPort()); try (HealthCheckedEndpointGroup endpointGroup = build( HealthCheckedEndpointGroup.builder(endpoint, "/no_ping_at_all"))) { Thread.sleep(3000); assertFirstRequest(healthCheckRequestLogs); // The second request must time out while long-polling. final RequestLog longPollingRequestLog = healthCheckRequestLogs.take().whenComplete().join(); assertThat(longPollingRequestLog.responseCause()).isInstanceOf(ResponseTimeoutException.class); // There must be no '102 Processing' headers received. final BlockingQueue<ResponseHeaders> receivedInformationals = longPollingRequestLog.context().attr(RECEIVED_INFORMATIONALS); assertThat(receivedInformationals).isEmpty(); // Eventually, the endpoint must stay healthy. assertThat(endpointGroup.endpoints()).isEmpty(); } }
Example #6
Source File: DnsAddressEndpointGroupTest.java From armeria with Apache License 2.0 | 6 votes |
@Test public void ipV6Only() throws Exception { try (TestDnsServer server = new TestDnsServer(ImmutableMap.of( new DefaultDnsQuestion("bar.com.", A), new DefaultDnsResponse(0).addRecord(ANSWER, newAddressRecord("bar.com.", "1.1.1.1")), new DefaultDnsQuestion("bar.com.", AAAA), new DefaultDnsResponse(0).addRecord(ANSWER, newAddressRecord("bar.com.", "::1")) .addRecord(ANSWER, newAddressRecord("bar.com.", "::1234:5678:90ab")) .addRecord(ANSWER, newAddressRecord("bar.com.", "2404:6800:4004:806::2013")) ))) { try (DnsAddressEndpointGroup group = DnsAddressEndpointGroup.builder("bar.com") .port(8080) .serverAddresses(server.addr()) .resolvedAddressTypes(ResolvedAddressTypes.IPV6_ONLY) .build()) { assertThat(group.whenReady().get(10, TimeUnit.SECONDS)).containsExactly( Endpoint.of("bar.com", 8080).withIpAddr("2404:6800:4004:806::2013"), Endpoint.of("bar.com", 8080).withIpAddr("::1"), Endpoint.of("bar.com", 8080).withIpAddr("::1234:5678:90ab")); } } }
Example #7
Source File: DnsAddressEndpointGroupTest.java From armeria with Apache License 2.0 | 6 votes |
@Test public void platformDefault() throws Exception { try (TestDnsServer server = new TestDnsServer(ImmutableMap.of( new DefaultDnsQuestion("baz.com.", A), new DefaultDnsResponse(0).addRecord(ANSWER, newAddressRecord("baz.com.", "1.1.1.1")), new DefaultDnsQuestion("baz.com.", AAAA), new DefaultDnsResponse(0).addRecord(ANSWER, newAddressRecord("baz.com.", "::1")) ))) { try (DnsAddressEndpointGroup group = DnsAddressEndpointGroup.builder("baz.com") .port(8080) .serverAddresses(server.addr()) .build()) { assertThat(group.whenReady().get()).contains( Endpoint.of("baz.com", 8080).withIpAddr("1.1.1.1")); } } }
Example #8
Source File: WeightedRoundRobinStrategyBenchmark.java From armeria with Apache License 2.0 | 6 votes |
@Setup public void setupCases() { final Random rand = new Random(); groupSameWeight = getEndpointGroup(generateEndpoints( id -> Endpoint.of("127.0.0.1", id + 1) .withWeight(300))); groupRandomMainly1Max30 = getEndpointGroup(generateEndpoints( id -> Endpoint.of("127.0.0.1", id + 1) .withWeight(1 + (id % 50 == 0 ? 29 : 0)))); groupRandomMax10 = getEndpointGroup(generateEndpoints( id -> Endpoint.of("127.0.0.1", id + 1) .withWeight(1 + rand.nextInt(10)))); groupRandomMax100 = getEndpointGroup(generateEndpoints( id -> Endpoint.of("127.0.0.1", id + 1) .withWeight(1 + rand.nextInt(100)))); groupUnique = getEndpointGroup(generateEndpoints( id -> Endpoint.of("127.0.0.1", id + 1) .withWeight(id + 1))); }
Example #9
Source File: ArmeriaCentralDogmaBuilderTest.java From centraldogma with Apache License 2.0 | 6 votes |
@Test void buildingWithProfile() throws Exception { final ArmeriaCentralDogmaBuilder b = new ArmeriaCentralDogmaBuilder(); b.healthCheckIntervalMillis(0); b.profile("xip"); final EndpointGroup group = b.endpointGroup(); assertThat(group).isNotNull(); assertThat(group).isInstanceOf(CompositeEndpointGroup.class); final CompositeEndpointGroup compositeGroup = (CompositeEndpointGroup) group; final List<EndpointGroup> childGroups = compositeGroup.groups(); assertThat(childGroups).hasSize(2); assertThat(childGroups.get(0)).isInstanceOf(DnsAddressEndpointGroup.class); assertThat(childGroups.get(1)).isInstanceOf(DnsAddressEndpointGroup.class); await().untilAsserted(() -> { final List<Endpoint> endpoints = group.endpoints(); assertThat(endpoints).isNotNull(); assertThat(endpoints).containsExactlyInAnyOrder( Endpoint.of("1.2.3.4.xip.io", 36462).withIpAddr("1.2.3.4"), Endpoint.of("5.6.7.8.xip.io", 8080).withIpAddr("5.6.7.8")); }); }
Example #10
Source File: HealthCheckedEndpointGroupAuthorityTest.java From armeria with Apache License 2.0 | 6 votes |
private HealthCheckedEndpointGroup build(Endpoint endpoint, Consumer<HealthCheckedEndpointGroupBuilder> customizer) { final HealthCheckedEndpointGroupBuilder builder = HealthCheckedEndpointGroup.builder(endpoint, HEALTH_CHECK_PATH); builder.withClientOptions(b -> { b.decorator(LoggingClient.newDecorator()); b.decorator((delegate, ctx, req) -> { // Record when health check requests were sent. logs.add(req.headers()); return delegate.execute(ctx, req); }); return b; }); customizer.accept(builder); return builder.build(); }
Example #11
Source File: CentralDogmaEndpointGroupTest.java From centraldogma with Apache License 2.0 | 6 votes |
@Test void text() throws Exception { try (Watcher<String> watcher = dogma.client().fileWatcher("directory", "my-service", Query.ofText("/endpoints.txt"))) { final CountDownLatch latch = new CountDownLatch(2); watcher.watch(unused -> latch.countDown()); final CentralDogmaEndpointGroup<String> endpointGroup = CentralDogmaEndpointGroup.ofWatcher( watcher, EndpointListDecoder.TEXT); endpointGroup.whenReady().get(); assertThat(endpointGroup.endpoints()).isEqualTo(ENDPOINT_LIST); assertThat(latch.getCount()).isOne(); dogma.client().push("directory", "my-service", Revision.HEAD, "commit", Change.ofTextUpsert("/endpoints.txt", "foo.bar:1234")) .join(); await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> assertThat(latch.getCount()).isZero()); assertThat(endpointGroup.endpoints()).containsExactly(Endpoint.of("foo.bar", 1234)); } }
Example #12
Source File: ZooKeeperEndpointGroupTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void legacyDiscoverySpec() throws Throwable { final List<Endpoint> sampleEndpoints = ZooKeeperTestUtil.sampleEndpoints(3); setLegacySpecNodeChildren(sampleEndpoints); final ZooKeeperEndpointGroup endpointGroup = endpointGroup(ZooKeeperDiscoverySpec.legacy()); await().untilAsserted(() -> assertThat(endpointGroup.endpoints()).hasSameElementsAs(sampleEndpoints)); // Add two more nodes. final List<Endpoint> extraEndpoints = ZooKeeperTestUtil.sampleEndpoints(2); setLegacySpecNodeChildren(extraEndpoints); // Construct the final expected node list. final Builder<Endpoint> builder = ImmutableSet.builder(); builder.addAll(sampleEndpoints).addAll(extraEndpoints); try (CloseableZooKeeper zk = zkInstance.connection()) { zk.sync(Z_NODE, (rc, path, ctx) -> {}, null); } final Set<Endpoint> expected = builder.build(); await().untilAsserted(() -> assertThat(endpointGroup.endpoints()).hasSameElementsAs(expected)); disconnectZk(endpointGroup); }
Example #13
Source File: CuratorDiscoverySpecTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void decode() { ZooKeeperDiscoverySpec spec = ZooKeeperDiscoverySpec.curator("foo"); ServiceInstance<?> instance = serviceInstance(false); Endpoint endpoint = spec.decode(CuratorXNodeValueCodec.INSTANCE.encode(instance)); assertThat(endpoint).isNull(); // enabled is false; instance = serviceInstance(true); endpoint = spec.decode(CuratorXNodeValueCodec.INSTANCE.encode(instance)); assertThat(endpoint).isEqualTo(Endpoint.of("foo.com", 100)); spec = ZooKeeperDiscoverySpec.builderForCurator("foo").useSsl(true).build(); endpoint = spec.decode(CuratorXNodeValueCodec.INSTANCE.encode(instance)); assertThat(endpoint).isEqualTo(Endpoint.of("foo.com", 200)); // useSsl final Endpoint bar = Endpoint.of("bar"); spec = ZooKeeperDiscoverySpec.builderForCurator("foo") .converter(serviceInstance -> bar) .build(); endpoint = spec.decode(CuratorXNodeValueCodec.INSTANCE.encode(instance)); assertThat(endpoint).isSameAs(bar); // Use converter. }
Example #14
Source File: AllHealthCheckStrategyTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void updateHealthWhenEndpointHealthyAndUnhealthy() { strategy.updateCandidates(candidates); final Endpoint candidate = candidates.get(0); boolean actUpdateRes = strategy.updateHealth(candidate, 0); List<Endpoint> actCandidates = strategy.getSelectedEndpoints(); assertThat(actUpdateRes).isFalse(); assertCandidates(actCandidates, candidates); actUpdateRes = strategy.updateHealth(candidate, 1); actCandidates = strategy.getSelectedEndpoints(); assertThat(actUpdateRes).isFalse(); assertCandidates(actCandidates, candidates); }
Example #15
Source File: CompositeEndpointGroup.java From armeria with Apache License 2.0 | 6 votes |
@Override public List<Endpoint> endpoints() { if (!dirty.get()) { return merged; } if (!dirty.compareAndSet(true, false)) { // Another thread might be updating merged at this time, but endpoint groups are allowed to take a // little bit of time to reflect updates. return merged; } final ImmutableList.Builder<Endpoint> newEndpoints = ImmutableList.builder(); for (EndpointGroup endpointGroup : endpointGroups) { newEndpoints.addAll(endpointGroup.endpoints()); } return merged = newEndpoints.build(); }
Example #16
Source File: ArmeriaRetrofitBuilder.java From armeria with Apache License 2.0 | 6 votes |
/** * Returns a newly-created {@link Retrofit} based on the properties of this builder. */ public Retrofit build() { final SessionProtocol protocol = webClient.scheme().sessionProtocol(); final ClientOptions retrofitOptions = buildOptions(webClient.options()); // Re-create the base client without a path, because Retrofit will always provide a full path. final WebClient baseWebClient = WebClient.builder(protocol, webClient.endpointGroup()) .options(retrofitOptions) .build(); if (nonBaseClientFactory == null) { nonBaseClientFactory = (p, url) -> WebClient.builder(p, Endpoint.of(url.host(), url.port())) .options(retrofitOptions) .build(); } retrofitBuilder.callFactory(new ArmeriaCallFactory( baseWebClientHost, baseWebClientPort, baseWebClient, streaming ? SubscriberFactory.streaming(callbackExecutor) : SubscriberFactory.blocking(), new CachedNonBaseClientFactory(nonBaseClientFactory) )); return retrofitBuilder.build(); }
Example #17
Source File: PartialHealthCheckStrategyTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void updateCandidates() { final List<Endpoint> newCandidates = createCandidates(5); maxCountStrategy.updateCandidates(newCandidates); assertCandidates(maxCountStrategy.getSelectedEndpoints(), newCandidates); final List<Endpoint> someOfOldCandidates = candidatesForMaxCount.subList(0, 3); maxCountStrategy.updateCandidates(someOfOldCandidates); assertCandidates(maxCountStrategy.getSelectedEndpoints(), someOfOldCandidates); final List<Endpoint> mixedCandidates = Streams.concat(createCandidates(2).stream(), someOfOldCandidates.stream()) .collect(toImmutableList()); maxCountStrategy.updateCandidates(mixedCandidates); assertCandidates(maxCountStrategy.getSelectedEndpoints(), mixedCandidates); }
Example #18
Source File: ClientUtil.java From armeria with Apache License 2.0 | 5 votes |
private static EndpointGroup mapEndpoint(ClientRequestContext ctx, EndpointGroup endpointGroup) { if (endpointGroup instanceof Endpoint) { return requireNonNull(ctx.options().endpointRemapper().apply((Endpoint) endpointGroup), "endpointRemapper returned null."); } else { return endpointGroup; } }
Example #19
Source File: PartialHealthCheckStrategyTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void getCandidates() { maxRatioStrategy.updateCandidates(candidatesForMaxRatio); final List<Endpoint> selectedCandidates = maxRatioStrategy.getSelectedEndpoints(); assertThat(selectedCandidates).hasSize(9); selectedCandidates.forEach( selectedCandidate -> assertThat(candidatesForMaxRatio).contains(selectedCandidate)); assertUniqueCandidates(selectedCandidates); }
Example #20
Source File: EurekaEndpointGroup.java From armeria with Apache License 2.0 | 5 votes |
@Override public List<Endpoint> apply(byte[] content) { try { return ImmutableList.of(endpoint(mapper.readValue(content, InstanceInfo.class), false)); } catch (IOException e) { throw new RuntimeException(e); } }
Example #21
Source File: CuratorServiceDiscoveryCompatibilityTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void registeredInstancesAreSameWhenUsingServiceDiscoveryImplAndUpdatingListener() throws Throwable { final Endpoint endpoint = ZooKeeperTestUtil.sampleEndpoints(1).get(0); final CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(zkInstance.connectString()) .retryPolicy(new ExponentialBackoffRetry(1000, 3)) .build(); client.start(); final JsonInstanceSerializer<Void> serializer = new JsonInstanceSerializer<>(Void.class); final ServiceInstance<Void> registered = serviceInstance(endpoint); final ServiceDiscoveryImpl<Void> serviceDiscovery = new ServiceDiscoveryImpl<>(client, Z_NODE, serializer, registered, false); serviceDiscovery.start(); assertInstance(registered); serviceDiscovery.close(); await().untilAsserted(() -> zkInstance.assertNotExists(Z_NODE + "/foo/bar")); final ZooKeeperRegistrationSpec registrationSpec = ZooKeeperRegistrationSpec.builderForCurator("foo") .serviceId("bar") .serviceAddress("foo.com") .port(endpoint.port()) .uriSpec(CURATOR_X_URI_SPEC) .build(); final ZooKeeperUpdatingListener listener = ZooKeeperUpdatingListener.builder(zkInstance.connectString(), Z_NODE, registrationSpec).build(); final Server server = Server.builder() .http(endpoint.port()) .service("/", (ctx, req) -> HttpResponse.of(200)) .build(); server.addListener(listener); server.start().join(); assertInstance(registered); server.stop().join(); client.close(); }
Example #22
Source File: HealthCheckedEndpointGroupTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void updatesSelectedCandidatesNoStackOverflowEvenUpdatesOnEqualThread() { final AtomicReference<HealthCheckerContext> firstSelectedCandidates = new AtomicReference<>(); final Function<? super HealthCheckerContext, ? extends AsyncCloseable> checkFactory = ctx -> { if (firstSelectedCandidates.get() == null) { firstSelectedCandidates.set(ctx); } ctx.updateHealth(HEALTHY); return AsyncCloseableSupport.of(); }; final Endpoint candidate1 = Endpoint.of("candidate1"); final Endpoint candidate2 = Endpoint.of("candidate2"); final MockEndpointGroup delegate = new MockEndpointGroup(); delegate.set(candidate1, candidate2); try (HealthCheckedEndpointGroup group = new HealthCheckedEndpointGroup(delegate, SessionProtocol.HTTP, 80, DEFAULT_HEALTH_CHECK_RETRY_BACKOFF, ClientOptions.of(), checkFactory, new InfinityUpdateHealthCheckStrategy())) { assertThat(group.healthyEndpoints).containsOnly(candidate1, candidate2); firstSelectedCandidates.get().updateHealth(UNHEALTHY); assertThat(group.healthyEndpoints).containsOnly(candidate2); } }
Example #23
Source File: HealthCheckedEndpointGroupCompatibilityTest.java From armeria with Apache License 2.0 | 5 votes |
private static void test(String path) { final Endpoint endpoint = Endpoint.of("127.0.0.1", server.httpPort()); try (HealthCheckedEndpointGroup endpointGroup = HealthCheckedEndpointGroup.of(endpoint, path)) { // Check the initial state (healthy). assertThat(endpointGroup.endpoints()).containsExactly(endpoint); } }
Example #24
Source File: ArmeriaCallFactory.java From armeria with Apache License 2.0 | 5 votes |
ArmeriaCallFactory(String baseWebClientHost, int baseWebClientPort, WebClient baseWebClient, SubscriberFactory subscriberFactory, BiFunction<? super SessionProtocol, ? super Endpoint, ? extends WebClient> nonBaseWebClientFactory) { this.baseWebClientHost = baseWebClientHost; this.baseWebClientPort = baseWebClientPort; this.baseWebClient = baseWebClient; this.subscriberFactory = subscriberFactory; @SuppressWarnings("unchecked") final BiFunction<SessionProtocol, Endpoint, WebClient> castNonBaseWebClientFactory = (BiFunction<SessionProtocol, Endpoint, WebClient>) nonBaseWebClientFactory; this.nonBaseWebClientFactory = castNonBaseWebClientFactory; }
Example #25
Source File: ZooKeeperTestUtil.java From armeria with Apache License 2.0 | 5 votes |
public static List<Endpoint> sampleEndpoints(int count) { final int[] ports = unusedPorts(count); final Builder<Endpoint> builder = ImmutableList.builder(); for (int i = 0; i < count; i++) { builder.add(Endpoint.of("127.0.0.1", ports[i]).withWeight(random.nextInt(10000) + 1)); } return builder.build(); }
Example #26
Source File: HealthCheckedEndpointGroupIntegrationTest.java From armeria with Apache License 2.0 | 5 votes |
/** * When an endpoint has an IP address already, the health checker must send a health check request using * an IP address, because otherwise the health checker can send the health check request to a wrong host * if there are more than one IP addresses assigned to the host name. */ @ParameterizedTest @EnumSource(value = SessionProtocol.class, names = { "HTTP", "HTTPS" }) void endpoints_customAuthority(SessionProtocol protocol) throws Exception { serverOne.start(); // This test case will fail if the health check does not use an IP address // because the host name 'foo' does not really exist. final int port = serverOne.port(protocol); try (HealthCheckedEndpointGroup endpointGroup = build( HealthCheckedEndpointGroup.builder( Endpoint.of("foo", port).withIpAddr("127.0.0.1"), HEALTH_CHECK_PATH), protocol)) { endpointGroup.newMeterBinder("qux").bindTo(registry); await().untilAsserted(() -> { assertThat(endpointGroup.endpoints()) .containsOnly(Endpoint.of("foo", port).withIpAddr("127.0.0.1")); assertThat(MoreMeters.measureAll(registry)) .containsEntry("armeria.client.endpoint.group.count#value{name=qux,state=healthy}", 1.0) .containsEntry("armeria.client.endpoint.group.count#value{name=qux,state=unhealthy}", 0.0) .containsEntry("armeria.client.endpoint.group.healthy#value" + "{authority=foo:" + port + ",ip=127.0.0.1,name=qux}", 1.0); }); } }
Example #27
Source File: KeyedCircuitBreakerMappingTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void hostSelector() throws Exception { assertThat(HOST.get(context(Endpoint.of("foo")), null)).isEqualTo("foo"); assertThat(HOST.get(context(Endpoint.of("foo", 8080)), null)).isEqualTo("foo:8080"); assertThat(HOST.get(context(Endpoint.of("foo").withIpAddr("1.2.3.4")), null)).isEqualTo("foo/1.2.3.4"); assertThat(HOST.get(context(Endpoint.of("1.2.3.4", 80)), null)).isEqualTo("1.2.3.4:80"); assertThat(HOST.get(context(Endpoint.of("::1", 80)), null)).isEqualTo("[::1]:80"); }
Example #28
Source File: RequestMetricSupportTest.java From armeria with Apache License 2.0 | 5 votes |
private static ClientRequestContext setupClientRequestCtx(MeterRegistry registry) { final ClientRequestContext ctx = ClientRequestContext.builder(HttpRequest.of(HttpMethod.POST, "/foo")) .meterRegistry(registry) .endpoint(Endpoint.of("example.com", 8080)) .connectionTimings(newConnectionTimings()) .build(); final MeterIdPrefixFunction meterIdPrefixFunction = MeterIdPrefixFunction.ofDefault("foo"); RequestMetricSupport.setup(ctx, REQUEST_METRICS_SET, meterIdPrefixFunction, false); return ctx; }
Example #29
Source File: DnsAddressEndpointGroupTest.java From armeria with Apache License 2.0 | 5 votes |
@Test public void backoffOnEmptyResponse() throws Exception { try (TestDnsServer server = new TestDnsServer(ImmutableMap.of( // Respond with empty records. new DefaultDnsQuestion("empty.com.", A), new DefaultDnsResponse(0), new DefaultDnsQuestion("empty.com.", AAAA), new DefaultDnsResponse(0) ))) { try (DnsAddressEndpointGroup group = DnsAddressEndpointGroup.builder("empty.com") .serverAddresses(server.addr()) .resolvedAddressTypes(ResolvedAddressTypes.IPV4_PREFERRED) .backoff(Backoff.fixed(500)) .build()) { await().untilAsserted(() -> assertThat(group.attemptsSoFar).isGreaterThan(2)); assertThat(group.endpoints()).isEmpty(); // Start to respond correctly. server.setResponses(ImmutableMap.of( new DefaultDnsQuestion("empty.com.", A), new DefaultDnsResponse(0) .addRecord(ANSWER, newAddressRecord("empty.com", "1.1.1.1", 1)), new DefaultDnsQuestion("empty.com.", AAAA), new DefaultDnsResponse(0) .addRecord(ANSWER, newAddressRecord("empty.com", "::1", 1)))); await().untilAsserted(() -> assertThat(group.endpoints()).containsExactly( Endpoint.of("empty.com").withIpAddr("1.1.1.1"), Endpoint.of("empty.com").withIpAddr("::1"))); } } }
Example #30
Source File: StaticEndpointGroup.java From armeria with Apache License 2.0 | 5 votes |
StaticEndpointGroup(EndpointSelectionStrategy selectionStrategy, Iterable<Endpoint> endpoints) { this.endpoints = ImmutableList.copyOf(requireNonNull(endpoints, "endpoints")); initialEndpointsFuture = CompletableFuture.completedFuture(this.endpoints); this.selectionStrategy = requireNonNull(selectionStrategy, "selectionStrategy"); selector = selectionStrategy.newSelector(this); }