Java Code Examples for io.grpc.ServerBuilder#build()
The following examples show how to use
io.grpc.ServerBuilder#build() .
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: GRPCServer.java From pravega with Apache License 2.0 | 6 votes |
/** * Create gRPC server on the specified port. * * @param controllerService The controller service implementation. * @param serverConfig The RPC Server config. * @param requestTracker Cache to track and access to client request identifiers. */ public GRPCServer(ControllerService controllerService, GRPCServerConfig serverConfig, RequestTracker requestTracker) { this.objectId = "gRPCServer"; this.config = serverConfig; GrpcAuthHelper authHelper = new GrpcAuthHelper(serverConfig.isAuthorizationEnabled(), serverConfig.getTokenSigningKey(), serverConfig.getAccessTokenTTLInSeconds()); ServerBuilder<?> builder = ServerBuilder .forPort(serverConfig.getPort()) .addService(ServerInterceptors.intercept(new ControllerServiceImpl(controllerService, authHelper, requestTracker, serverConfig.isReplyWithStackTraceOnError()), RPCTracingHelpers.getServerInterceptor(requestTracker))); if (serverConfig.isAuthorizationEnabled()) { this.authHandlerManager = new AuthHandlerManager(serverConfig); this.authHandlerManager.registerInterceptors(builder); } else { this.authHandlerManager = null; } if (serverConfig.isTlsEnabled() && !Strings.isNullOrEmpty(serverConfig.getTlsCertFile())) { builder = builder.useTransportSecurity(new File(serverConfig.getTlsCertFile()), new File(serverConfig.getTlsKeyFile())); } this.server = builder.build(); }
Example 2
Source File: GrpcStartable.java From txle with Apache License 2.0 | 6 votes |
GrpcStartable(GrpcServerConfig serverConfig, Tracing tracing, BindableService... services) { ServerBuilder<?> serverBuilder; if (serverConfig.isSslEnable()) { serverBuilder = NettyServerBuilder.forAddress( new InetSocketAddress(serverConfig.getHost(), serverConfig.getPort())); try { ((NettyServerBuilder) serverBuilder).sslContext(getSslContextBuilder(serverConfig).build()); } catch (SSLException e) { throw new IllegalStateException("Unable to setup grpc to use SSL.", e); } } else { serverBuilder = ServerBuilder.forPort(serverConfig.getPort()); } // Arrays.stream(services).forEach(serverBuilder::addService); // add interceptor for grpc server By Gannalyo Arrays.stream(services).forEach(service -> serverBuilder.addService(ServerInterceptors.intercept(service, GrpcTracing.create(tracing).newServerInterceptor()))); server = serverBuilder.build(); }
Example 3
Source File: GrpcEmbeddedServer.java From micronaut-grpc with Apache License 2.0 | 6 votes |
/** * Default constructor. * @param applicationContext The application context * @param applicationConfiguration The application configuration * @param grpcServerConfiguration The GRPC server configuration * @param serverBuilder The server builder * @param eventPublisher The event publisher * @param computeInstanceMetadataResolver The computed instance metadata * @param metadataContributors The metadata contributors */ @Internal GrpcEmbeddedServer( @Nonnull ApplicationContext applicationContext, @Nonnull ApplicationConfiguration applicationConfiguration, @Nonnull GrpcServerConfiguration grpcServerConfiguration, @Nonnull ServerBuilder<?> serverBuilder, @Nonnull ApplicationEventPublisher eventPublisher, @Nullable ComputeInstanceMetadataResolver computeInstanceMetadataResolver, @Nullable List<ServiceInstanceMetadataContributor> metadataContributors) { ArgumentUtils.requireNonNull("applicationContext", applicationContext); ArgumentUtils.requireNonNull("applicationConfiguration", applicationConfiguration); ArgumentUtils.requireNonNull("grpcServerConfiguration", grpcServerConfiguration); this.applicationContext = applicationContext; this.configuration = applicationConfiguration; this.grpcConfiguration = grpcServerConfiguration; this.eventPublisher = eventPublisher; this.server = serverBuilder.build(); this.computeInstanceMetadataResolver = computeInstanceMetadataResolver; this.metadataContributors = metadataContributors; }
Example 4
Source File: TitusGrpcServer.java From titus-control-plane with Apache License 2.0 | 6 votes |
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 5
Source File: SimulatedCloudGrpcServer.java From titus-control-plane with Apache License 2.0 | 6 votes |
@PostConstruct public void start() { if (!started.getAndSet(true)) { ServerBuilder serverBuilder = configure(ServerBuilder.forPort(configuration.getGrpcPort())); serverBuilder .addService(ServerInterceptors.intercept(simulatedAgentsService, createInterceptors(SimulatedAgentServiceGrpc.getServiceDescriptor()))) .addService(ServerInterceptors.intercept(simulatedMesosService, createInterceptors(SimulatedMesosServiceGrpc.getServiceDescriptor()))); this.server = serverBuilder.build(); logger.info("Starting gRPC server on port {}.", configuration.getGrpcPort()); try { this.server.start(); } catch (final IOException e) { throw new RuntimeException(e); } logger.info("Started gRPC server on port {}.", configuration.getGrpcPort()); } }
Example 6
Source File: GrpcEmbeddedServer.java From micronaut-grpc with Apache License 2.0 | 6 votes |
/** * Default constructor. * @param applicationContext The application context * @param applicationConfiguration The application configuration * @param grpcServerConfiguration The GRPC server configuration * @param serverBuilder The server builder * @param eventPublisher The event publisher * @param computeInstanceMetadataResolver The computed instance metadata * @param metadataContributors The metadata contributors */ @Internal GrpcEmbeddedServer( @Nonnull ApplicationContext applicationContext, @Nonnull ApplicationConfiguration applicationConfiguration, @Nonnull GrpcServerConfiguration grpcServerConfiguration, @Nonnull ServerBuilder<?> serverBuilder, @Nonnull ApplicationEventPublisher eventPublisher, @Nullable ComputeInstanceMetadataResolver computeInstanceMetadataResolver, @Nullable List<ServiceInstanceMetadataContributor> metadataContributors) { ArgumentUtils.requireNonNull("applicationContext", applicationContext); ArgumentUtils.requireNonNull("applicationConfiguration", applicationConfiguration); ArgumentUtils.requireNonNull("grpcServerConfiguration", grpcServerConfiguration); this.applicationContext = applicationContext; this.configuration = applicationConfiguration; this.grpcConfiguration = grpcServerConfiguration; this.eventPublisher = eventPublisher; this.server = serverBuilder.build(); this.computeInstanceMetadataResolver = computeInstanceMetadataResolver; this.metadataContributors = metadataContributors; }
Example 7
Source File: SagaLoadBalancedSenderTest.java From servicecomb-pack with Apache License 2.0 | 5 votes |
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 8
Source File: DefaultGrpcServerFactory.java From spring-boot-starter-grpc with Apache License 2.0 | 5 votes |
@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 9
Source File: Server.java From africastalking-java with MIT License | 5 votes |
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 10
Source File: SimpleGrpcServerFactory.java From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public Server buildServerForServices(int port, Collection<BindableService> services) { ServerBuilder builder = ServerBuilder.forPort(port); setupServer(builder); services.forEach(service -> registerService(builder, service)); return builder.build(); }
Example 11
Source File: TccLoadBalanceSenderTest.java From servicecomb-pack with Apache License 2.0 | 5 votes |
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 12
Source File: GrpcTestServer.java From Sentinel with Apache License 2.0 | 5 votes |
void start(int port, boolean shouldIntercept) throws IOException { if (server != null) { throw new IllegalStateException("Server already running!"); } ServerBuilder<?> serverBuild = ServerBuilder.forPort(port) .addService(new FooServiceImpl()); if (shouldIntercept) { serverBuild.intercept(new SentinelGrpcServerInterceptor()); } server = serverBuild.build(); server.start(); }
Example 13
Source File: GeoWaveGrpcServer.java From geowave with Apache License 2.0 | 5 votes |
/** 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 14
Source File: GrpcTestServer.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 5 votes |
void start(int port, boolean shouldIntercept) throws IOException { if (server != null) { throw new IllegalStateException("Server already running!"); } ServerBuilder<?> serverBuild = ServerBuilder.forPort(port) .addService(new FooServiceImpl()); if (shouldIntercept) { serverBuild.intercept(new SentinelGrpcServerInterceptor()); } server = serverBuild.build(); server.start(); }
Example 15
Source File: LoadBalancedClusterMessageSenderTest.java From txle with Apache License 2.0 | 5 votes |
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 16
Source File: LoadServer.java From grpc-nebula-java with Apache License 2.0 | 4 votes |
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 17
Source File: TestMain.java From java-control-plane with Apache License 2.0 | 4 votes |
/** * Example minimal xDS implementation using the java-control-plane lib. * * @param arg command-line args */ public static void main(String[] arg) throws IOException, InterruptedException { SimpleCache<String> cache = new SimpleCache<>(node -> GROUP); cache.setSnapshot( GROUP, Snapshot.create( ImmutableList.of( Cluster.newBuilder() .setName("cluster0") .setConnectTimeout(Duration.newBuilder().setSeconds(5)) .setType(DiscoveryType.STATIC) .addHosts(Address.newBuilder() .setSocketAddress(SocketAddress.newBuilder().setAddress("127.0.0.1").setPortValue(1234))) .build()), ImmutableList.of(), ImmutableList.of(), ImmutableList.of(), ImmutableList.of(), "1")); DiscoveryServer discoveryServer = new DiscoveryServer(cache); ServerBuilder builder = NettyServerBuilder.forPort(12345) .addService(discoveryServer.getAggregatedDiscoveryServiceImpl()) .addService(discoveryServer.getClusterDiscoveryServiceImpl()) .addService(discoveryServer.getEndpointDiscoveryServiceImpl()) .addService(discoveryServer.getListenerDiscoveryServiceImpl()) .addService(discoveryServer.getRouteDiscoveryServiceImpl()); Server server = builder.build(); server.start(); System.out.println("Server has started on port " + server.getPort()); Runtime.getRuntime().addShutdownHook(new Thread(server::shutdown)); Thread.sleep(10000); cache.setSnapshot( GROUP, Snapshot.create( ImmutableList.of( Cluster.newBuilder() .setName("cluster1") .setConnectTimeout(Duration.newBuilder().setSeconds(5)) .setType(DiscoveryType.STATIC) .addHosts(Address.newBuilder() .setSocketAddress(SocketAddress.newBuilder().setAddress("127.0.0.1").setPortValue(1235))) .build()), ImmutableList.of(), ImmutableList.of(), ImmutableList.of(), ImmutableList.of(), "1")); server.awaitTermination(); }
Example 18
Source File: SentinelRlsGrpcServer.java From Sentinel with Apache License 2.0 | 4 votes |
public SentinelRlsGrpcServer(int port) { ServerBuilder<?> builder = ServerBuilder.forPort(port) .addService(new SentinelEnvoyRlsServiceImpl()); server = builder.build(); }
Example 19
Source File: LoadServer.java From grpc-java with Apache License 2.0 | 4 votes |
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 20
Source File: GRPCServer.java From conductor with Apache License 2.0 | 4 votes |
public GRPCServer(int port, BindableService... services) { ServerBuilder<?> builder = ServerBuilder.forPort(port); Arrays.stream(services).forEach(builder::addService); server = builder.build(); }