com.linecorp.armeria.server.Server Java Examples

The following examples show how to use com.linecorp.armeria.server.Server. 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: THttpClientTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void serviceAddedIsCalled() {
    final AtomicReference<ServiceConfig> cfgHolder = new AtomicReference<>();
    final THttpService tHttpService =
            ThriftCallService.of((AsyncIface) (name, cb) -> cb.onComplete("name"))
                             .decorate(delegate -> new SimpleDecoratingRpcService(delegate) {
                                 @Override
                                 public void serviceAdded(ServiceConfig cfg) throws Exception {
                                     cfgHolder.set(cfg);
                                 }

                                 @Override
                                 public RpcResponse serve(
                                         ServiceRequestContext ctx, RpcRequest req) throws Exception {
                                     return new CompletableRpcResponse();
                                 }
                             }).decorate(THttpService.newDecorator());
    Server.builder().service("/", tHttpService).build();

    final ServiceConfig serviceConfig = cfgHolder.get();
    assertThat(serviceConfig).isNotNull();
    assertThat(serviceConfig.service()).isInstanceOf(THttpService.class);

    final ThriftCallService thriftCallService = tHttpService.as(ThriftCallService.class);
    assertThat(thriftCallService).isNotNull();
}
 
Example #2
Source File: EurekaUpdatingListener.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public void serverStopping(Server server) throws Exception {
    closed = true;
    final ScheduledFuture<?> heartBeatFuture = this.heartBeatFuture;
    if (heartBeatFuture != null) {
        heartBeatFuture.cancel(false);
    }
    final String appName = this.appName;
    if (appName != null) {
        final String instanceId = instanceInfo.getInstanceId();
        assert instanceId != null;
        client.cancel(appName, instanceId).aggregate().handle((res, cause) -> {
            if (cause != null) {
                logger.warn("Failed to deregister from Eureka: {}", client.uri(), cause);
            } else if (!res.status().isSuccess()) {
                logger.warn("Failed to deregister from Eureka: {} (status: {}, content: {})",
                            client.uri(), res.status(), res.contentUtf8());
            }
            return null;
        });
    }
}
 
Example #3
Source File: PooledResponseBufferBenchmark.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Setup
public void startServer() throws Exception {
    final ServerBuilder sb =
            Server.builder()
                  .service("/a", THttpService.of((AsyncIface) (name, cb) -> cb.onComplete(RESPONSE))
                                             .decorate(PooledDecoratingService::new))
                  .service("/b", THttpService.of((AsyncIface) (name, cb) -> cb.onComplete(RESPONSE))
                                             .decorate(UnpooledDecoratingService::new));
    server = sb.build();
    server.start().join();

    final int httpPort = server.activeLocalPort(SessionProtocol.HTTP);
    pooledClient = Clients.newClient("tbinary+http://127.0.0.1:" + httpPort + "/a",
                                     HelloService.Iface.class);
    unpooledClient = Clients.newClient("tbinary+http://127.0.0.1:" + httpPort + "/b",
                                       HelloService.Iface.class);
}
 
Example #4
Source File: ManagedTomcatService.java    From armeria with Apache License 2.0 6 votes vote down vote up
void stop() throws Exception {
    final org.apache.catalina.Server server = this.server;
    final Connector connector = this.connector;
    this.server = null;
    this.connector = null;

    if (engineName != null) {
        activeEngines.remove(engineName);
        engineName = null;
    }

    if (server == null || !started) {
        return;
    }

    try {
        logger.info("Stopping an embedded Tomcat: {}", toString(server));
        server.stop();
    } catch (Exception e) {
        logger.warn("Failed to stop an embedded Tomcat: {}", toString(server), e);
    }

    postStopTask.accept(connector);
}
 
Example #5
Source File: HttpResponseHeaderConversionBenchmark.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Setup
public void startServer() {
    final int port = 8080;

    serverWithAdditionalHeaders = Server.builder()
                                        .http(port)
                                        .service("/header_conversion", (ctx, req) -> {
                       addAdditionalHeaders(ctx);
                       addProhibitedHeaders(ctx);
                       return HttpResponse.of(HttpStatus.OK);
                   })
                                        .build();
    serverWithAdditionalHeaders.start().join();

    clientWithoutAdditionalHeadersHttp1 = WebClient.of("h1c://127.0.0.1:" + port);
    clientWithoutAdditionalHeadersHttp2 = WebClient.of("h2c://127.0.0.1:" + port);
}
 
Example #6
Source File: AbstractArmeriaBeanPostProcessor.java    From armeria with Apache License 2.0 6 votes vote down vote up
private LocalArmeriaPortElement(Member member, AnnotatedElement ae, @Nullable PropertyDescriptor pd) {
    super(member, pd);
    final LocalArmeriaPort localArmeriaPort = ae.getAnnotation(LocalArmeriaPort.class);
    final SessionProtocol protocol = localArmeriaPort.value();
    Server server = getServer();
    if (server == null) {
        server = beanFactory.getBean(Server.class);
        serServer(server);
    }

    Integer port = portCache.get(protocol);
    if (port == null) {
        port = server.activeLocalPort(protocol);
        portCache.put(protocol, port);
    }
    this.port = port;
}
 
Example #7
Source File: Main.java    From Jax-RS-Performance-Comparison with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    HelloService.AsyncIface helloHandler = new HelloService.AsyncIface(){
        @Override
        public void hello(AsyncMethodCallback resultHandler) throws TException {
            resultHandler.onComplete("Hello world");
        }
    };

    ServerBuilder sb = new ServerBuilder();
    sb.port(8080, SessionProtocol.HTTP);
    sb.serviceAt("/hello", ThriftService.of(helloHandler, SerializationFormat.THRIFT_BINARY))
            .serviceUnder("/docs/", new DocService());

    Server server= sb.build();
    server.start();
}
 
Example #8
Source File: Main.java    From armeria with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final SamlServiceProvider ssp = samlServiceProvider();
    final Server server =
            Server.builder()
                  .https(8443)
                  // You can add this certificate to your trust store
                  // in order to make your web browser happy.
                  .tls(new File(ClassLoader.getSystemResource("localhost.crt").toURI()),
                       new File(ClassLoader.getSystemResource("localhost.key").toURI()))
                  // Decorate you service with SAML decorator.
                  .annotatedService("/", new MyService(), ssp.newSamlDecorator())
                  // Add SAML service to your server which handles a SAML response and a metadata request.
                  .service(ssp.newSamlService())
                  .build();

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        server.stop().join();
        logger.info("Server has been stopped.");
    }));

    server.start().join();
    logger.info("Server has been started.");
}
 
Example #9
Source File: Main.java    From armeria with Apache License 2.0 6 votes vote down vote up
static Server newServer(int httpPort, int httpsPort) throws Exception {
    return Server.builder()
                 .http(httpPort)
                 .https(httpsPort)
                 .tlsSelfSigned()
                 // Serve an individual file.
                 .service("/favicon.ico",
                          HttpFile.of(Main.class.getClassLoader(), "favicon.ico")
                                  .asService())
                 // Serve the files under the current user's home directory.
                 .service("prefix:/",
                          FileService.builder(Paths.get(System.getProperty("user.home")))
                                     .autoIndex(true)
                                     .build())
                 .build();
}
 
Example #10
Source File: Main.java    From armeria with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final Server backend = Server.builder()
                                 .service("/square/{num}", (ctx, req) -> {
                                     final long num = Long.parseLong(ctx.pathParam("num"));
                                     return HttpResponse.of(Long.toString(num * num));
                                 })
                                 .http(8081)
                                 .build();

    final WebClient backendClient = WebClient.of("http://localhost:8081");

    final Server frontend =
            Server.builder()
                  .http(8080)
                  .serviceUnder("/", new MainService(backendClient))
                  .build();

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        backend.stop().join();
        frontend.stop().join();
    }));

    backend.start().join();
    frontend.start().join();
}
 
Example #11
Source File: Main.java    From armeria with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final Server backend = Server.builder()
                                 .service("/square/{num}", ((ctx, req) -> {
                                     final long num = Long.parseLong(ctx.pathParam("num"));
                                     return HttpResponse.of(Long.toString(num * num));
                                 }))
                                 .http(8081)
                                 .build();

    final Server frontend = DaggerMain_MainComponent.create().server();

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        backend.stop().join();
        frontend.stop().join();
    }));

    backend.start().join();
    frontend.start().join();
}
 
Example #12
Source File: Main.java    From armeria with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final Server backend = Server.builder()
                                 .service("/square/{num}", ((ctx, req) -> {
                                     final long num = Long.parseLong(ctx.pathParam("num"));
                                     return HttpResponse.of(Long.toString(num * num));
                                 }))
                                 .http(8081)
                                 .build();

    final WebClient backendClient = WebClient.of("http://localhost:8081");

    final Server frontend =
            Server.builder()
                  .http(8080)
                  .serviceUnder("/", new MainService(backendClient))
                  .build();

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        backend.stop().join();
        frontend.stop().join();
    }));

    backend.start().join();
    frontend.start().join();
}
 
Example #13
Source File: ServerSetRegistrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void noSequential() throws Throwable {
    final List<Endpoint> endpoints = ZooKeeperTestUtil.sampleEndpoints(1);
    final ServerSetsRegistrationSpecBuilder specBuilder =
            ZooKeeperRegistrationSpec.builderForServerSets();
    final ZooKeeperRegistrationSpec spec =
            specBuilder.serviceEndpoint(Endpoint.of("127.0.0.1", endpoints.get(0).port()))
                       .nodeName("foo")
                       .sequential(false)
                       .build();
    final ZooKeeperUpdatingListener listener =
            ZooKeeperUpdatingListener.builder(zkInstance.connectString(), Z_NODE, spec).build();
    final Server server = Server.builder()
                                .serverListener(listener)
                                .http(endpoints.get(0).port())
                                .service("/", (ctx, req) -> HttpResponse.of(200))
                                .build();
    server.start().join();

    try (CloseableZooKeeper zk = zkInstance.connection()) {
        // nodeName is not sequential.
        await().untilAsserted(() -> zkInstance.assertExists(Z_NODE + "/foo"));
    }
    server.stop().join();
    await().untilAsserted(() -> zkInstance.assertNotExists(Z_NODE + "/foo"));
}
 
Example #14
Source File: HBaseClientCompatibilityTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Ensure Armeria's dependencies do not cause a trouble with hbase-shaded-client.
 *
 * @see <a href="https://issues.apache.org/jira/browse/HBASE-14963">HBASE-14963</a>
 */
@Test(expected = NotAllMetaRegionsOnlineException.class)
public void testGuavaConflict() throws Exception {
    // Make sure Armeria is available in the class path.
    assertThat(Version.getAll(Server.class.getClassLoader())).isNotNull();
    // Make sure newer Guava is available in the class path.
    assertThat(Stopwatch.class.getDeclaredConstructor().getModifiers()).is(new Condition<>(
            value -> !Modifier.isPublic(value),
            "Recent Guava Stopwatch should have non-public default constructor."));

    final MetaTableLocator locator = new MetaTableLocator();
    final ZooKeeperWatcher zkw = mock(ZooKeeperWatcher.class);
    final RecoverableZooKeeper zk = mock(RecoverableZooKeeper.class);
    when(zkw.getRecoverableZooKeeper()).thenReturn(zk);
    when(zk.exists(any(), any())).thenReturn(new Stat(0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0));

    locator.waitMetaRegionLocation(zkw, 100);
}
 
Example #15
Source File: ZooKeeperRegistrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static List<Server> startServers(boolean endpointRegistrationSpec) {
    final List<Server> servers = new ArrayList<>();
    for (int i = 0; i < sampleEndpoints.size(); i++) {
        final Server server = Server.builder()
                                    .http(sampleEndpoints.get(i).port())
                                    .service("/", (ctx, req) -> HttpResponse.of(200))
                                    .build();
        final ZooKeeperRegistrationSpec registrationSpec;
        if (endpointRegistrationSpec) {
            registrationSpec = ZooKeeperRegistrationSpec.legacy(sampleEndpoints.get(i));
        } else {
            registrationSpec = ZooKeeperRegistrationSpec.builderForCurator(CURATOR_X_SERVICE_NAME)
                                                        .serviceId(String.valueOf(i))
                                                        .serviceAddress(CURATOR_X_ADDRESS)
                                                        .build();
        }
        final ServerListener listener =
                ZooKeeperUpdatingListener.builder(zkInstance.connectString(), Z_NODE, registrationSpec)
                                         .sessionTimeoutMillis(SESSION_TIMEOUT_MILLIS)
                                         .build();
        server.addListener(listener);
        server.start().join();
        servers.add(server);
    }
    return servers;
}
 
Example #16
Source File: ZooKeeperRegistrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static void validateOneNodeRemoved(
        List<Server> servers, CloseableZooKeeper zk, boolean endpointRegistrationSpec) throws Throwable {
    servers.get(0).stop().get();
    servers.remove(0);

    int removed = 0;
    int remaining = 0;

    for (int i = 0; i < sampleEndpoints.size(); i++) {
        final String key;
        if (endpointRegistrationSpec) {
            key = Z_NODE + '/' + sampleEndpoints.get(i).host() + '_' + sampleEndpoints.get(i).port();
        } else {
            key = Z_NODE + '/' + CURATOR_X_SERVICE_NAME + '/' + i;
        }
        if (zk.exists(key).get()) {
            remaining++;
        } else {
            removed++;
        }
    }

    assertThat(removed).isOne();
    assertThat(remaining).isEqualTo(sampleEndpoints.size() - 1);
}
 
Example #17
Source File: ZooKeeperRegistrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void legacyZooKeeperRegistrationSpec() throws Throwable {
    final List<Server> servers = startServers(true);
    // all servers start and with znode created
    await().untilAsserted(() -> sampleEndpoints.forEach(
            endpoint -> zkInstance.assertExists(Z_NODE + '/' + endpoint.host() + '_' + endpoint.port())));

    try (CloseableZooKeeper zk = zkInstance.connection()) {
        for (Endpoint sampleEndpoint : sampleEndpoints) {
            assertThat(ZooKeeperDiscoverySpec.legacy().decode(zk.getData(
                    Z_NODE + '/' + sampleEndpoint.host() + '_' + sampleEndpoint.port()).get()))
                    .isEqualTo(sampleEndpoint);
        }
        validateOneNodeRemoved(servers, zk, true);
    }
    servers.forEach(s -> s.stop().join());
}
 
Example #18
Source File: ZooKeeperUpdatingListener.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static ZooKeeperRegistrationSpec serverSetsSpec(
        ServerSetsRegistrationSpec spec, Server server) {
    final ServerSetsInstance serverSetsInstance = spec.serverSetsInstance();
    if (serverSetsInstance.serviceEndpoint() != null) {
        warnIfInactivePort(server, serverSetsInstance.serviceEndpoint().port(), null);
        return spec;
    }
    final ServerSetsRegistrationSpecBuilder builder =
            ZooKeeperRegistrationSpec.builderForServerSets();
    builder.serviceEndpoint(defaultEndpoint(server))
           .additionalEndpoints(serverSetsInstance.additionalEndpoints())
           .metadata(serverSetsInstance.metadata())
           .sequential(spec.isSequential())
           .nodeName(spec.path().substring(1)); // Simply remove prepended '/'.
    final Integer shardId = serverSetsInstance.shardId();
    if (shardId != null) {
        builder.shardId(shardId);
    }
    return builder.build();
}
 
Example #19
Source File: Main.java    From armeria with Apache License 2.0 5 votes vote down vote up
static Server newProxyServer(int httpPort, int httpsPort) throws Exception {
    return Server.builder()
                 .http(httpPort)
                 .https(httpsPort)
                 .tlsSelfSigned()
                 // Disable timeout to serve infinite streaming response.
                 .requestTimeoutMillis(0)
                 .serviceUnder("/", new ProxyService())
                 .decorator(LoggingService.newDecorator())
                 .build();
}
 
Example #20
Source File: SamlPortConfigAutoFiller.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public void serverStarted(Server server) throws Exception {
    // Ensure that the following work will be done once.
    if (completed.compareAndSet(false, true)) {
        final ServerPort activePort = server.activePort();
        assert activePort != null;
        builder.setSchemeAndPortIfAbsent(activePort);
        assert builder.scheme() != null;
        config = new SamlPortConfig(builder.scheme(), builder.port());
        future.complete(config);
    }
}
 
Example #21
Source File: Main.java    From armeria with Apache License 2.0 5 votes vote down vote up
static Server newServer(int httpPort, int httpsPort) throws Exception {
    final HelloRequest exampleRequest = HelloRequest.newBuilder().setName("Armeria").build();
    final HttpServiceWithRoutes grpcService =
            GrpcService.builder()
                       .addService(new HelloServiceImpl())
                       // See https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md
                       .addService(ProtoReflectionService.newInstance())
                       .supportedSerializationFormats(GrpcSerializationFormats.values())
                       .enableUnframedRequests(true)
                       // You can set useBlockingTaskExecutor(true) in order to execute all gRPC
                       // methods in the blockingTaskExecutor thread pool.
                       // .useBlockingTaskExecutor(true)
                       .build();
    return Server.builder()
                 .http(httpPort)
                 .https(httpsPort)
                 .tlsSelfSigned()
                 .service(grpcService)
                 // You can access the documentation service at http://127.0.0.1:8080/docs.
                 // See https://armeria.dev/docs/server-docservice for more information.
                 .serviceUnder("/docs",
                         DocService.builder()
                                   .exampleRequestForMethod(
                                           HelloServiceGrpc.SERVICE_NAME,
                                           "Hello", exampleRequest)
                                   .exampleRequestForMethod(
                                           HelloServiceGrpc.SERVICE_NAME,
                                           "LazyHello", exampleRequest)
                                   .exampleRequestForMethod(
                                           HelloServiceGrpc.SERVICE_NAME,
                                           "BlockingHello", exampleRequest)
                                   .exclude(DocServiceFilter.ofServiceName(
                                           ServerReflectionGrpc.SERVICE_NAME))
                                   .build())
                 .build();
}
 
Example #22
Source File: GracefulShutdownIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testHardTimeout() throws Exception {
    final long baselineNanos = baselineNanos();
    final Server server = GracefulShutdownIntegrationTest.server.start();

    final SleepService.Iface client = newClient();
    // Send the first request to warm up the client connection, because otherwise
    // the quiet period may end while the client establishes a connection on a busy machine.
    client.sleep(0);

    final CompletableFuture<Long> stopFuture = CompletableFuture.supplyAsync(() -> {
        logger.debug("Server shutting down");
        final long startTime = System.nanoTime();
        server.stop().join();
        final long stopTime = System.nanoTime();
        logger.debug("Server shut down");
        return stopTime - startTime;
    });

    // Keep sending a request while shutting down so that the hard limit is reached.
    for (int i = 1;; i++) {
        try {
            client.sleep(50);
        } catch (Exception e) {
            // Server has been shut down
            logger.debug("Client detected server shutdown after {} calls:", i, e);
            break;
        }
    }

    // Should take 1 more second than the baseline, because the requests will extend the quiet period
    // until the shutdown timeout is triggered.
    assertThat(stopFuture.join()).isBetween(baselineNanos + MILLISECONDS.toNanos(600),
                                            baselineNanos + MILLISECONDS.toNanos(1400));
}
 
Example #23
Source File: Main.java    From armeria with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    final Server server = newServer(8080, 8443);

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        server.stop().join();
        logger.info("Server has been stopped.");
    }));

    server.start().join();

    logger.info("Server has been started. Serving DocService at http://127.0.0.1:{}/docs",
                server.activeLocalPort());
}
 
Example #24
Source File: DownstreamSimpleBenchmark.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    server = Server.builder()
                   .serviceUnder("/",
                                 GrpcService.builder()
                                            .addService(new GithubApiService()).build())
                                            .requestTimeout(Duration.ZERO)
                                            .meterRegistry(NoopMeterRegistry.get())
                                            .build();
    server.start().join();
    final String url = "gproto+http://127.0.0.1:" + port() + '/';
    githubApiClient = Clients.newClient(url, GithubServiceBlockingStub.class);
    githubApiFutureClient = Clients.newClient(url, GithubServiceFutureStub.class);
}
 
Example #25
Source File: ZooKeeperRegistrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void curatorRegistrationSpec() throws Throwable {
    final List<Server> servers = startServers(false);
    // all servers start and with znode created
    await().untilAsserted(() -> {
        for (int i = 0; i < 3; i++) {
            zkInstance.assertExists(Z_NODE + '/' + CURATOR_X_SERVICE_NAME + '/' + i);
        }
    });

    try (CloseableZooKeeper zk = zkInstance.connection()) {
        for (int i = 0; i < sampleEndpoints.size(); i++) {
            final CompletableFuture<ServiceInstance<?>> instanceCaptor = new CompletableFuture<>();
            final ZooKeeperDiscoverySpec discoverySpec =
                    ZooKeeperDiscoverySpec.builderForCurator(CURATOR_X_SERVICE_NAME)
                                          .converter(serviceInstance -> {
                                     instanceCaptor.complete(serviceInstance);
                                     return null;
                                 }).build();
            discoverySpec.decode(zk.getData(Z_NODE + '/' + CURATOR_X_SERVICE_NAME + '/' + i).get());
            final ServiceInstance<?> actual = instanceCaptor.join();
            final ServiceInstance<Object> expected = expectedInstance(servers, i);
            assertThat(actual).isEqualToIgnoringGivenFields(expected, "registrationTimeUTC");
        }
        validateOneNodeRemoved(servers, zk, false);
    }
    servers.forEach(s -> s.stop().join());
}
 
Example #26
Source File: HttpRequestHeaderConversionBenchmark.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Setup
public void startServer() {
    final int port = 8080;

    serverWithoutAdditionalHeaders = Server.builder()
                                           .http(port)
                                           .service("/header_conversion", (ctx, req) -> {
                                               return HttpResponse.of(HttpStatus.OK);
                                           })
                                           .build();
    serverWithoutAdditionalHeaders.start().join();

    clientWithAdditionalHeadersHttp1 = WebClient.builder("h1c://127.0.0.1:" + port)
                                                .decorator(((delegate, ctx, req) -> {
                                                    addAdditionalHeaders(ctx);
                                                    addProhibitedHeaders(ctx);
                                                    addCookies(ctx);
                                                    return delegate.execute(ctx, req);
                                                })).build();

    clientWithAdditionalHeadersHttp2 = WebClient.builder("h2c://127.0.0.1:" + port)
                                                .decorator(((delegate, ctx, req) -> {
                                                    addAdditionalHeaders(ctx);
                                                    addProhibitedHeaders(ctx);
                                                    addCookies(ctx);
                                                    return delegate.execute(ctx, req);
                                                })).build();
}
 
Example #27
Source File: SimpleBenchmarkBase.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Setup
public void start() throws Exception {
    server = Server.builder()
                   .https(0)
                   .service("/empty", (ctx, req) -> HttpResponse.of("\"\""))
                   .tlsSelfSigned()
                   .build();
    server.start().join();
    client = newClient();
}
 
Example #28
Source File: KafkaStorageIT.java    From zipkin-storage-kafka with Apache License 2.0 5 votes vote down vote up
@BeforeEach void setUp() throws Exception {
  consumerConfig = new Properties();
  consumerConfig.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_BOOTSTRAP_SERVERS);
  consumerConfig.put(ConsumerConfig.GROUP_ID_CONFIG, "test");
  consumerConfig.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class);
  consumerConfig.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class);

  assertThat(kafkaContainer.isRunning()).isTrue();

  traceTimeout = Duration.ofSeconds(5);
  int serverPort = randomPort();
  storageBuilder = KafkaStorage.newBuilder()
      .bootstrapServers(KAFKA_BOOTSTRAP_SERVERS)
      .storageStateDir("target/zipkin_" + System.currentTimeMillis())
      .hostname("localhost")
      .serverPort(serverPort);
  storageBuilder.spanAggregation.traceTimeout(traceTimeout);
  storage = (KafkaStorage) storageBuilder.build();
  server = Server.builder()
      .annotatedService("/storage/kafka", new KafkaStorageHttpService(storage))
      .http(serverPort)
      .build();
  server.start();

  Collection<NewTopic> newTopics = new ArrayList<>();
  newTopics.add(new NewTopic(storageBuilder.spanAggregation.spansTopic, 1, (short) 1));
  newTopics.add(new NewTopic(storageBuilder.spanAggregation.traceTopic, 1, (short) 1));
  newTopics.add(new NewTopic(storageBuilder.spanAggregation.dependencyTopic, 1, (short) 1));
  storage.getAdminClient().createTopics(newTopics).all().get();

  await().atMost(10, TimeUnit.SECONDS).until(() -> storage.check().ok());
  storage.checkResources();
  Properties producerConfig = new Properties();
  producerConfig.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_BOOTSTRAP_SERVERS);
  tracesProducer = new KafkaProducer<>(producerConfig, new StringSerializer(),
    spansSerde.serializer());
  dependencyProducer = new KafkaProducer<>(producerConfig, new StringSerializer(),
    dependencyLinkSerde.serializer());
}
 
Example #29
Source File: HttpServerBenchmark.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Setup
public void startServer() throws Exception {
    server = Server.builder()
                   .service("/empty", (ctx, req) -> HttpResponse.of(HttpStatus.OK))
                   .requestTimeout(Duration.ZERO)
                   .meterRegistry(NoopMeterRegistry.get())
                   .build();
    server.start().join();
    final ServerPort httpPort = server.activePorts().values().stream()
                                      .filter(ServerPort::hasHttp).findAny()
                                      .get();
    webClient = Clients.newClient("none+" + protocol.uriText() + "://127.0.0.1:" +
                                  httpPort.localAddress().getPort() + '/',
                                  WebClient.class);
}
 
Example #30
Source File: Main.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
static Server server(Provider<MainGraph.Component.Builder> graphBuilder) {
    return Server.builder()
                 .http(8080)
                 .serviceUnder("/", ((ctx, req) ->
                         HttpResponse.from(
                                 ListenableFuturesExtra.toCompletableFuture(
                                         graphBuilder.get().request(req).build().execute()))))
                 .build();
}