Java Code Examples for io.grpc.ServerBuilder#addService()

The following examples show how to use io.grpc.ServerBuilder#addService() . 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: TitusGrpcServer.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
public TitusGrpcServer build() {
    Preconditions.checkArgument(port >= 0, "Port number is negative");
    Preconditions.checkNotNull(titusRuntime, "TitusRuntime not set");

    List<ServerInterceptor> commonInterceptors = new ArrayList<>();
    commonInterceptors.add(new CommonErrorCatchingServerInterceptor(new GrpcExceptionMapper(serviceExceptionMappers)));
    GrpcFitInterceptor.getIfFitEnabled(titusRuntime).ifPresent(commonInterceptors::add);
    commonInterceptors.addAll(interceptors);

    ServerBuilder serverBuilder = ServerBuilder.forPort(port);
    if (serverConfigurer != null) {
        serverBuilder = serverConfigurer.apply(serverBuilder);
    }
    for (ServiceBuilder serviceBuilder : serviceBuilders.values()) {
        serverBuilder.addService(serviceBuilder.build(commonInterceptors));
    }

    return new TitusGrpcServer(serverBuilder.build(), shutdownTime);
}
 
Example 2
Source File: NettyFlowControlTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
private void startServer(int serverFlowControlWindow) {
  ServerBuilder<?> builder =
      NettyServerBuilder.forAddress(new InetSocketAddress("localhost", 0))
      .flowControlWindow(serverFlowControlWindow);
  builder.addService(ServerInterceptors.intercept(
      new TestServiceImpl(Executors.newScheduledThreadPool(2)),
      ImmutableList.<ServerInterceptor>of()));
  try {
    server = builder.build().start();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 3
Source File: LoadBalancedClusterMessageSenderTest.java    From txle with Apache License 2.0 5 votes vote down vote up
private static void startServerOnPort(int port) {
  ServerBuilder<?> serverBuilder = ServerBuilder.forPort(port);
  serverBuilder.addService(new MyTxEventService(connected.get(port), eventsMap.get(port), delays.get(port)));
  Server server = serverBuilder.build();

  try {
    server.start();
    servers.put(port, server);
  } catch (IOException e) {
    fail(e.getMessage());
  }
}
 
Example 4
Source File: GRpcServerApplicationRunner.java    From faster-framework-project with Apache License 2.0 5 votes vote down vote up
@Override
public void run(ApplicationArguments args) throws Exception {
    List<BindServiceAdapter> bindServiceAdapterList = serverBuilderConfigure.getBindServiceAdapterList();
    if (CollectionUtils.isEmpty(bindServiceAdapterList)) {
        log.info("GRpc server services empty.GRpc server is not start.");
        return;
    }
    ServerBuilder serverBuilder = serverBuilderConfigure.serverBuilder();
    for (BindServiceAdapter bindServiceAdapter : bindServiceAdapterList) {
        serverBuilder.addService(bindServiceAdapter);
    }
    this.server = serverBuilder.build().start();
    startDaemonAwaitThread();
    log.info("GRpc start success, listening on port {}.", serverBuilderConfigure.getPort());
}
 
Example 5
Source File: SagaLoadBalancedSenderTest.java    From servicecomb-pack with Apache License 2.0 5 votes vote down vote up
private static void startServerOnPort(int port) {
  ServerBuilder<?> serverBuilder = ServerBuilder.forPort(port);
  serverBuilder.addService(new MyTxEventService(connected.get(port), eventsMap.get(port), delays.get(port)));
  Server server = serverBuilder.build();

  try {
    server.start();
    servers.put(port, server);
  } catch (IOException e) {
    fail(e.getMessage());
  }
}
 
Example 6
Source File: TccLoadBalanceSenderTest.java    From servicecomb-pack with Apache License 2.0 5 votes vote down vote up
private static void startServerOnPort(int port) {
  ServerBuilder<?> serverBuilder = NettyServerBuilder.forAddress(
      new InetSocketAddress("127.0.0.1", port));
  serverBuilder.addService(new MyTccEventServiceImpl(connected.get(port), eventsMap.get(port), delays.get(port)));
  Server server = serverBuilder.build();

  try {
    server.start();
    servers.put(port, server);
  } catch (Exception ex) {
    fail(ex.getMessage());
  }
}
 
Example 7
Source File: NettyFlowControlTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private void startServer(int serverFlowControlWindow) {
  ServerBuilder<?> builder =
      NettyServerBuilder
          .forAddress(new InetSocketAddress("localhost", 0))
          .initialFlowControlWindow(serverFlowControlWindow);
  builder.addService(ServerInterceptors.intercept(
      new TestServiceImpl(Executors.newScheduledThreadPool(2)),
      ImmutableList.<ServerInterceptor>of()));
  try {
    server = builder.build().start();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 8
Source File: Server.java    From africastalking-java with MIT License 5 votes vote down vote up
public void start(File certChainFile, File privateKeyFile, int port) throws IOException {
    ServerBuilder builder = ServerBuilder.forPort(port).useTransportSecurity(certChainFile, privateKeyFile);
    if (mAuthenticator != null) {
        builder.addService(ServerInterceptors.intercept(
            mSdkService, new AuthenticationInterceptor(this.mAuthenticator)));
    } else {
        builder.addService(mSdkService);
    }
    mGrpc = builder.build();
    mGrpc.start();
}
 
Example 9
Source File: Server.java    From africastalking-java with MIT License 5 votes vote down vote up
public void startInsecure(int port) throws IOException {
    ServerBuilder builder = ServerBuilder.forPort(port);
    if (mAuthenticator != null) {
        builder.addService(ServerInterceptors.intercept(
            mSdkService, new AuthenticationInterceptor(this.mAuthenticator)));
    } else {
        builder.addService(mSdkService);
    }
    mGrpc = builder.build();
    mGrpc.start();
}
 
Example 10
Source File: DefaultGrpcServerFactory.java    From spring-boot-starter-grpc with Apache License 2.0 5 votes vote down vote up
@Override
public Server createServer() {
	ServerBuilder builder = ServerBuilder.forPort(getPort());
	Collection<GrpcServiceDefinition> definitions = discoverer.findGrpcServices();
	for (GrpcServiceDefinition definition : definitions) {
		ServiceDescriptor descriptor = definition.getService().bindService().getServiceDescriptor();
		logger.info("Registered gRPC service: " + descriptor.getName()
				+ ", bean: " + definition.getBeanName() + ", class: "
				+ definition.getService().getClass().getName());
		builder.addService(definition.getService());
	}

	return builder.build();
}
 
Example 11
Source File: GrpcServer.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void start() {
    checkState(server == null);
    try {
        ServerBuilder builder = ServerBuilder.forPort(port);
        for (ServerServiceDefinition serviceDefinition : serviceDefinitions) {
            LOG.info("Starting {} service on port {}.", serviceDefinition.getServiceDescriptor().getName(), port);
            builder.addService(serviceDefinition);
        }
        server = builder.build().start();
        LOG.info("Server started.");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 12
Source File: GeoWaveGrpcServer.java    From geowave with Apache License 2.0 5 votes vote down vote up
/** Start serving requests. */
public void start(final int port) throws IOException {
  final ServerBuilder<?> builder = NettyServerBuilder.forPort(port);
  builder.addService(ProtoReflectionService.newInstance());
  try {
    final Iterator<GeoWaveGrpcServiceSpi> grpcServices = serviceLoader.iterator();
    while (grpcServices.hasNext()) {
      final GeoWaveGrpcServiceSpi s = grpcServices.next();
      builder.addService(s.getBindableService());
    }
  } catch (final ServiceConfigurationError e) {
    LOGGER.error("Exception encountered initializing services for gRPC server", e);
  }

  server = builder.build();
  server.start();
  LOGGER.info("Server started, listening on " + port);

  Runtime.getRuntime().addShutdownHook(new Thread() {
    @Override
    public void run() {
      // Use stderr here since the logger may have been reset
      // by its JVM shutdown hook.
      System.err.println("*** shutting down gRPC server since JVM is shutting down");
      GeoWaveGrpcServer.this.stop();
      System.err.println("*** server shut down");
    }
  });
}
 
Example 13
Source File: LoadServer.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
LoadServer(Control.ServerConfig config) throws Exception {
  log.log(Level.INFO, "Server Config \n" + config.toString());
  port = config.getPort() ==  0 ? Utils.pickUnusedPort() : config.getPort();
  ServerBuilder<?> serverBuilder = ServerBuilder.forPort(port);
  int asyncThreads = config.getAsyncServerThreads() == 0
      ? Runtime.getRuntime().availableProcessors()
      : config.getAsyncServerThreads();
  // The concepts of sync & async server are quite different in the C impl and the names
  // chosen for the enum are based on that implementation. We use 'sync' to mean
  // the direct executor case in Java even though the service implementations are always
  // fully async.
  switch (config.getServerType()) {
    case ASYNC_SERVER: {
      serverBuilder.executor(getExecutor(asyncThreads));
      break;
    }
    case SYNC_SERVER: {
      serverBuilder.directExecutor();
      break;
    }
    case ASYNC_GENERIC_SERVER: {
      serverBuilder.executor(getExecutor(asyncThreads));
      // Create buffers for the generic service
      PooledByteBufAllocator alloc = PooledByteBufAllocator.DEFAULT;
      genericResponse = alloc.buffer(config.getPayloadConfig().getBytebufParams().getRespSize());
      if (genericResponse.capacity() > 0) {
        genericResponse.writerIndex(genericResponse.capacity() - 1);
      }
      break;
    }
    default: {
      throw new IllegalArgumentException();
    }
  }
  if (config.hasSecurityParams()) {
    File cert = TestUtils.loadCert("server1.pem");
    File key = TestUtils.loadCert("server1.key");
    serverBuilder.useTransportSecurity(cert, key);
  }
  benchmarkService = new AsyncServer.BenchmarkServiceImpl();
  if (config.getServerType() == Control.ServerType.ASYNC_GENERIC_SERVER) {
    serverBuilder.addService(
        ServerServiceDefinition
            .builder(new ServiceDescriptor(BenchmarkServiceGrpc.SERVICE_NAME,
                GENERIC_STREAMING_PING_PONG_METHOD))
            .addMethod(GENERIC_STREAMING_PING_PONG_METHOD, new GenericServiceCallHandler())
            .build());
  } else {
    serverBuilder.addService(benchmarkService);
  }
  server = serverBuilder.build();

  List<OperatingSystemMXBean> beans =
      ManagementFactory.getPlatformMXBeans(OperatingSystemMXBean.class);
  if (!beans.isEmpty()) {
    osBean = beans.get(0);
  } else {
    osBean = null;
  }
}
 
Example 14
Source File: App.java    From modeldb with Apache License 2.0 4 votes vote down vote up
private static void wrapService(ServerBuilder<?> serverBuilder, BindableService bindableService) {
  App app = App.getInstance();
  if (app.traceEnabled)
    serverBuilder.addService(app.tracingInterceptor.intercept(bindableService));
  else serverBuilder.addService(bindableService);
}
 
Example 15
Source File: GRpcServersWrapper.java    From grpc-spring-boot-starter with MIT License 4 votes vote down vote up
private void addServiceToServer(Object expectedGRpcServiceBean, ServerBuilder serverBuilder) {
//    ServerServiceDefinition serviceDefinition = invokeBindMethod(expectedGRpcServiceBean, method);
    BindableService asBindableService = (BindableService) expectedGRpcServiceBean;
    serverBuilder.addService(asBindableService);
    log.info("Add service {} to {}", expectedGRpcServiceBean, serverBuilder);
  }
 
Example 16
Source File: SimpleGrpcServerFactory.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Override this method to override how a {@link BindableService} is added to the {@link ServerBuilder}.
 */
protected void registerService(ServerBuilder builder, BindableService service) {
    builder.addService(service);
}
 
Example 17
Source File: LoadServer.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
LoadServer(Control.ServerConfig config) throws Exception {
  log.log(Level.INFO, "Server Config \n" + config.toString());
  port = config.getPort() ==  0 ? Utils.pickUnusedPort() : config.getPort();
  ServerBuilder<?> serverBuilder = ServerBuilder.forPort(port);
  int asyncThreads = config.getAsyncServerThreads() == 0
      ? Runtime.getRuntime().availableProcessors()
      : config.getAsyncServerThreads();
  // The concepts of sync & async server are quite different in the C impl and the names
  // chosen for the enum are based on that implementation. We use 'sync' to mean
  // the direct executor case in Java even though the service implementations are always
  // fully async.
  switch (config.getServerType()) {
    case ASYNC_SERVER: {
      serverBuilder.executor(getExecutor(asyncThreads));
      break;
    }
    case SYNC_SERVER: {
      serverBuilder.directExecutor();
      break;
    }
    case ASYNC_GENERIC_SERVER: {
      serverBuilder.executor(getExecutor(asyncThreads));
      // Create buffers for the generic service
      PooledByteBufAllocator alloc = PooledByteBufAllocator.DEFAULT;
      genericResponse = alloc.buffer(config.getPayloadConfig().getBytebufParams().getRespSize());
      if (genericResponse.capacity() > 0) {
        genericResponse.writerIndex(genericResponse.capacity() - 1);
      }
      break;
    }
    default: {
      throw new IllegalArgumentException();
    }
  }
  if (config.hasSecurityParams()) {
    File cert = TestUtils.loadCert("server1.pem");
    File key = TestUtils.loadCert("server1.key");
    serverBuilder.useTransportSecurity(cert, key);
  }
  benchmarkService = new AsyncServer.BenchmarkServiceImpl();
  if (config.getServerType() == Control.ServerType.ASYNC_GENERIC_SERVER) {
    serverBuilder.addService(
        ServerServiceDefinition
            .builder(new ServiceDescriptor(BenchmarkServiceGrpc.SERVICE_NAME,
                GENERIC_STREAMING_PING_PONG_METHOD))
            .addMethod(GENERIC_STREAMING_PING_PONG_METHOD, new GenericServiceCallHandler())
            .build());
  } else {
    serverBuilder.addService(benchmarkService);
  }
  server = serverBuilder.build();

  List<OperatingSystemMXBean> beans =
      ManagementFactory.getPlatformMXBeans(OperatingSystemMXBean.class);
  if (!beans.isEmpty()) {
    osBean = beans.get(0);
  } else {
    osBean = null;
  }
}