下面列出了怎么用io.grpc.protobuf.services.ProtoReflectionService的API类实例代码及写法,或者点击链接到github查看源代码。
private void start() throws IOException {
/* The port on which the server should run */
int port = 50051;
server = ServerBuilder.forPort(port)
.addService(ProtoReflectionService.newInstance())
.addService(new GreeterImpl()).build().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");
ProtoApplication.this.stop();
System.err.println("*** server shut down");
}
});
}
private void start() throws IOException {
/* The port on which the server should run */
int port = 50051;
server = ServerBuilder.forPort(port)
.addService(ProtoReflectionService.newInstance())
.addService(new GreeterImpl()).build().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");
ProtoApplication.this.stop();
System.err.println("*** server shut down");
}
});
}
@Inject
LocalServer(
@Named("Server log path") String logPath,
AuthService authService,
CodeReviewService codeReviewService) {
if (logToFile.get()) {
// TODO: Figure out how to also direct Flogger to log file.
try {
PrintStream logStream = new PrintStream(logPath);
System.setOut(logStream);
System.setErr(logStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
server =
ServerBuilder.forPort(localServerPort.get())
.addService(authService)
.addService(codeReviewService)
.addService(ProtoReflectionService.newInstance())
.build();
}
@Bean
@Lazy
InfoContributor grpcInfoContributor(final GrpcServerProperties properties,
final Collection<BindableService> grpcServices, final HealthStatusManager healthStatusManager) {
final Map<String, Object> details = new LinkedHashMap<>();
details.put("port", properties.getPort());
if (properties.isReflectionServiceEnabled()) {
// Only expose services via web-info if we do the same via grpc.
final Map<String, List<String>> services = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
details.put("services", services);
final List<BindableService> mutableGrpcServiceList = new ArrayList<>(grpcServices);
mutableGrpcServiceList.add(ProtoReflectionService.newInstance());
if (properties.isHealthServiceEnabled()) {
mutableGrpcServiceList.add(healthStatusManager.getHealthService());
}
for (final BindableService grpcService : mutableGrpcServiceList) {
final ServiceDescriptor serviceDescriptor = grpcService.bindService().getServiceDescriptor();
final List<String> methods = collectMethodNamesForService(serviceDescriptor);
services.put(serviceDescriptor.getName(), methods);
}
}
return new SimpleInfoContributor("grpc.server", details);
}
/**
* Configures the services that should be served by the server.
*
* @param builder The server builder to configure.
*/
protected void configureServices(final T builder) {
// support health check
if (this.properties.isHealthServiceEnabled()) {
builder.addService(this.healthStatusManager.getHealthService());
}
if (this.properties.isReflectionServiceEnabled()) {
builder.addService(ProtoReflectionService.newInstance());
}
for (final GrpcServiceDefinition service : this.serviceList) {
final String serviceName = service.getDefinition().getServiceDescriptor().getName();
log.info("Registered gRPC service: " + serviceName + ", bean: " + service.getBeanName() + ", class: "
+ service.getBeanClazz().getName());
builder.addService(service.getDefinition());
this.healthStatusManager.setStatus(serviceName, HealthCheckResponse.ServingStatus.SERVING);
}
}
private GRPCServer buildGRPCServer(GRPCServerConfiguration grpcServerConfiguration) {
ImmutableList.Builder<BindableService> services = ImmutableList.<BindableService>builder().add(
healthServiceImpl,
eventServiceImpl,
metadataServiceImpl,
taskServiceImpl,
workflowServiceImpl);
if (grpcServerConfiguration.isReflectionEnabled()) {
services.add(ProtoReflectionService.newInstance());
}
return new GRPCServer(
grpcServerConfiguration.getPort(),
services.build().toArray(new BindableService[]{})
);
}
@Bean
@Lazy
InfoContributor grpcInfoContributor(final GrpcServerProperties properties,
final Collection<BindableService> grpcServices, final HealthStatusManager healthStatusManager) {
final Map<String, Object> details = new LinkedHashMap<>();
details.put("port", properties.getPort());
if (properties.isReflectionServiceEnabled()) {
// Only expose services via web-info if we do the same via grpc.
final Map<String, List<String>> services = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
details.put("services", services);
final List<BindableService> mutableGrpcServiceList = new ArrayList<>(grpcServices);
mutableGrpcServiceList.add(ProtoReflectionService.newInstance());
if (properties.isHealthServiceEnabled()) {
mutableGrpcServiceList.add(healthStatusManager.getHealthService());
}
for (final BindableService grpcService : mutableGrpcServiceList) {
final ServiceDescriptor serviceDescriptor = grpcService.bindService().getServiceDescriptor();
final List<String> methods = collectMethodNamesForService(serviceDescriptor);
services.put(serviceDescriptor.getName(), methods);
}
}
return new SimpleInfoContributor("grpc.server", details);
}
/**
* Configures the services that should be served by the server.
*
* @param builder The server builder to configure.
*/
protected void configureServices(final T builder) {
// support health check
if (this.properties.isHealthServiceEnabled()) {
builder.addService(this.healthStatusManager.getHealthService());
}
if (this.properties.isReflectionServiceEnabled()) {
builder.addService(ProtoReflectionService.newInstance());
}
for (final GrpcServiceDefinition service : this.serviceList) {
final String serviceName = service.getDefinition().getServiceDescriptor().getName();
log.info("Registered gRPC service: " + serviceName + ", bean: " + service.getBeanName() + ", class: "
+ service.getBeanClazz().getName());
builder.addService(service.getDefinition());
this.healthStatusManager.setStatus(serviceName, HealthCheckResponse.ServingStatus.SERVING);
}
}
/** Create a RouteGuide server using serverBuilder as a base and features as data. */
private MetaStoreServer(String configPath, ServerBuilder<?> serverBuilder, int port)
throws IOException {
MetaStore metaStore = new MetaStore(configPath);
this.port = port;
server =
serverBuilder
.addService(new MetaStoreService(metaStore))
.addService(new RegistryService(metaStore))
.addService(ProtoReflectionService.newInstance())
.build();
}
public static void main(String[] args) throws Exception {
logger.info("Starting server on port " + DEMO_SERVER_PORT);
Server server = ServerBuilder.forPort(DEMO_SERVER_PORT)
.addService(ProtoReflectionService.newInstance())
.addService(new HelloServiceImpl())
.build()
.start();
server.awaitTermination();
}
public static void main(String[] args) throws Exception {
logger.info("Starting server on port " + DEMO_SERVER_PORT);
Server server = ServerBuilder.forPort(DEMO_SERVER_PORT)
.addService(ProtoReflectionService.newInstance())
.addService(new HelloServiceImpl())
.build()
.start();
server.awaitTermination();
}
@Override
public void run(String... args) throws Exception {
log.info("Starting gRPC Server ...");
Collection<ServerInterceptor> globalInterceptors = getBeanNamesByTypeWithAnnotation(GRpcGlobalInterceptor.class, ServerInterceptor.class)
.map(name -> applicationContext.getBeanFactory().getBean(name, ServerInterceptor.class))
.collect(Collectors.toList());
// Adding health service
serverBuilder.addService(healthStatusManager.getHealthService());
// find and register all GRpcService-enabled beans
getBeanNamesByTypeWithAnnotation(GRpcService.class, BindableService.class)
.forEach(name -> {
BindableService srv = applicationContext.getBeanFactory().getBean(name, BindableService.class);
ServerServiceDefinition serviceDefinition = srv.bindService();
GRpcService gRpcServiceAnn = applicationContext.findAnnotationOnBean(name, GRpcService.class);
serviceDefinition = bindInterceptors(serviceDefinition, gRpcServiceAnn, globalInterceptors);
serverBuilder.addService(serviceDefinition);
String serviceName = serviceDefinition.getServiceDescriptor().getName();
healthStatusManager.setStatus(serviceName, HealthCheckResponse.ServingStatus.SERVING);
log.info("'{}' service has been registered.", srv.getClass().getName());
});
if (gRpcServerProperties.isEnableReflection()) {
serverBuilder.addService(ProtoReflectionService.newInstance());
log.info("'{}' service has been registered.", ProtoReflectionService.class.getName());
}
configurator.accept(serverBuilder);
server = serverBuilder.build().start();
applicationContext.publishEvent(new GRpcServerInitializedEvent(applicationContext,server));
log.info("gRPC Server started, listening on port {}.", server.getPort());
startDaemonAwaitThread();
}
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://line.github.io/armeria/server-docservice.html 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();
}
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();
}
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();
}
/**
* Adds a gRPC {@link BindableService} to this {@link GrpcServiceBuilder}. Most gRPC service
* implementations are {@link BindableService}s.
*/
public GrpcServiceBuilder addService(BindableService bindableService) {
if (bindableService instanceof ProtoReflectionService) {
checkState(protoReflectionServiceInterceptor == null,
"Attempting to add a ProtoReflectionService but one is already present. " +
"ProtoReflectionService must only be added once.");
protoReflectionServiceInterceptor = new ProtoReflectionServiceInterceptor();
return addService(ServerInterceptors.intercept(bindableService, protoReflectionServiceInterceptor));
}
return addService(bindableService.bindService());
}
/** 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");
}
});
}
private void start() throws Exception {
health = new HealthStatusManager();
server =
NettyServerBuilder.forPort(port)
.addService(new TestServiceImpl(serverId))
.addService(new XdsUpdateHealthServiceImpl(health))
.addService(health.getHealthService())
.addService(ProtoReflectionService.newInstance())
.build()
.start();
health.setStatus("", ServingStatus.SERVING);
}
@Override
public void initialize(GenericApplicationContext applicationContext) {
var environment = applicationContext.getEnvironment();
if (!environment.acceptsProfiles(Profiles.of("gateway"))) {
return;
}
var serverProperties = PropertiesUtil.bind(environment, new GRpcServerProperties());
if (!serverProperties.isEnabled()) {
return;
}
applicationContext.registerBean(GRPCLiiklusService.class);
applicationContext.registerBean(
Server.class,
() -> {
var serverBuilder = NettyServerBuilder
.forPort(serverProperties.getPort())
.permitKeepAliveTime(150, TimeUnit.SECONDS)
.permitKeepAliveWithoutCalls(true)
.directExecutor()
.intercept(new ServerInterceptor() {
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
call.setCompression("gzip");
return next.startCall(call, headers);
}
})
.addService(ProtoReflectionService.newInstance());
for (var bindableService : applicationContext.getBeansOfType(BindableService.class).values()) {
serverBuilder.addService(bindableService);
}
for (var transportConfigurer : applicationContext.getBeansOfType(GRPCLiiklusTransportConfigurer.class).values()) {
transportConfigurer.apply(serverBuilder);
}
return serverBuilder.build();
},
it -> {
it.setInitMethodName("start");
it.setDestroyMethodName("shutdownNow");
}
);
}
@PostConstruct
public void start() {
if (started.getAndSet(true)) {
return;
}
this.port = config.getGrpcPort();
this.server = configure(ServerBuilder.forPort(port).executor(grpcCallbackExecutor))
.addService(ServerInterceptors.intercept(
healthService,
createInterceptors(HealthGrpc.getServiceDescriptor())
))
.addService(ServerInterceptors.intercept(
schedulerService,
createInterceptors(SchedulerServiceGrpc.getServiceDescriptor())
))
.addService(ServerInterceptors.intercept(
jobManagementService,
createInterceptors(JobManagementServiceGrpc.getServiceDescriptor())
))
.addService(ServerInterceptors.intercept(
autoScalingService,
createInterceptors(AutoScalingServiceGrpc.getServiceDescriptor())
))
.addService(ServerInterceptors.intercept(
loadBalancerService,
createInterceptors(LoadBalancerServiceGrpc.getServiceDescriptor())))
.addService(
ServerInterceptors.intercept(
reactorServerFactory.apply(
MachineServiceGrpc.getServiceDescriptor(),
reactorMachineGrpcService
),
createInterceptors(MachineServiceGrpc.getServiceDescriptor())
)
)
.addService(ProtoReflectionService.newInstance())
.build();
LOG.info("Starting gRPC server on port {}.", port);
try {
this.server.start();
this.port = server.getPort();
} catch (final IOException e) {
throw new RuntimeException(e);
}
LOG.info("Started gRPC server on port {}.", port);
}
@PostConstruct
public void start() {
if (started.getAndSet(true)) {
return;
}
this.port = config.getPort();
this.server = configure(ServerBuilder.forPort(port).executor(grpcCallbackExecutor))
.addService(ServerInterceptors.intercept(
healthService,
createInterceptors(HealthGrpc.getServiceDescriptor())
))
.addService(ServerInterceptors.intercept(
jobManagementService,
createInterceptors(JobManagementServiceGrpc.getServiceDescriptor())
))
.addService(ServerInterceptors.intercept(
evictionService,
createInterceptors(EvictionServiceGrpc.getServiceDescriptor())
))
.addService(ServerInterceptors.intercept(
agentManagementService,
createInterceptors(AgentManagementServiceGrpc.getServiceDescriptor())
))
.addService(ServerInterceptors.intercept(
appAutoScalingService,
createInterceptors(AutoScalingServiceGrpc.getServiceDescriptor())
))
.addService(ServerInterceptors.intercept(
schedulerService,
createInterceptors(SchedulerServiceGrpc.getServiceDescriptor())
))
.addService(ServerInterceptors.intercept(
reactorServerFactory.apply(
MachineServiceGrpc.getServiceDescriptor(),
reactorMachineGrpcService
),
createInterceptors(MachineServiceGrpc.getServiceDescriptor())
))
.addService(ServerInterceptors.intercept(
loadBalancerService,
createInterceptors(LoadBalancerServiceGrpc.getServiceDescriptor())
))
.addService(ProtoReflectionService.newInstance())
.build();
LOG.info("Starting gRPC server on port {}.", port);
try {
this.server.start();
this.port = server.getPort();
} catch (final IOException e) {
throw new RuntimeException(e);
}
LOG.info("Started gRPC server on port {}.", port);
}
@Override
protected void configure(ServerBuilder sb) throws Exception {
sb.workerGroup(EventLoopGroups.newEventLoopGroup(1), true);
sb.maxRequestLength(0);
sb.service(
GrpcService.builder()
.setMaxInboundMessageSizeBytes(MAX_MESSAGE_SIZE)
.addService(ServerInterceptors.intercept(
new UnitTestServiceImpl(),
REPLACE_EXCEPTION, ADD_TO_CONTEXT))
.enableUnframedRequests(true)
.supportedSerializationFormats(GrpcSerializationFormats.values())
.build(),
service -> service
.decorate(LoggingService.newDecorator())
.decorate((delegate, ctx, req) -> {
ctx.log().whenComplete().thenAccept(requestLogQueue::add);
return delegate.serve(ctx, req);
}));
// For simplicity, mount onto subpaths with custom options
sb.serviceUnder(
"/json-preserving/",
GrpcService.builder()
.addService(new UnitTestServiceImpl())
.supportedSerializationFormats(GrpcSerializationFormats.values())
.jsonMarshallerFactory(serviceDescriptor -> {
return GrpcJsonMarshaller.builder()
.jsonMarshallerCustomizer(marshaller -> {
marshaller.preservingProtoFieldNames(true);
})
.build(serviceDescriptor);
})
.build());
sb.serviceUnder(
"/no-client-timeout/",
GrpcService.builder()
.addService(new UnitTestServiceImpl())
.useClientTimeoutHeader(false)
.build());
sb.service(
GrpcService.builder()
.addService(ProtoReflectionService.newInstance())
.build(),
service -> service.decorate(LoggingService.newDecorator()));
}