下面列出了io.grpc.ServerInterceptor#io.grpc.ServerBuilder 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void start() throws IOException {
/* The port on which the server should run */
int port = 50051;
server = ServerBuilder.forPort(port).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");
HelloWorldServer.this.stop();
System.err.println("*** server shut down");
}
});
}
void init(@Nullable ServerInterceptor userInterceptor) throws IOException {
stop();
// tracing interceptor needs to go last
ServerInterceptor tracingInterceptor = grpcTracing.newServerInterceptor();
ServerInterceptor[] interceptors = userInterceptor != null
? new ServerInterceptor[] {userInterceptor, tracingInterceptor}
: new ServerInterceptor[] {tracingInterceptor};
server = ServerBuilder.forPort(PickUnusedPort.get())
.addService(ServerInterceptors.intercept(new GreeterImpl(grpcTracing), interceptors))
.build().start();
client = usePlainText(ManagedChannelBuilder.forAddress("localhost", server.getPort()))
.build();
}
private void start() throws IOException {
// 使用ServerBuilder来构建和启动服务,通过使用forPort方法来指定监听的地址和端口
// 创建一个实现方法的服务GreeterImpl的实例,并通过addService方法将该实例纳入
// 调用build() start()方法构建和启动rpcserver
server = ServerBuilder.forPort(port)
.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");
HelloServer.this.stop();
System.err.println("*** server shut down");
}
});
}
private void start() throws IOException {
server = ServerBuilder.forPort(port)
.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");
HelloWorldServer.this.stop();
System.err.println("*** server shut down");
}
});
}
private void start() throws IOException {
server = ServerBuilder.forPort(PORT)
.addService(ServerInterceptors.intercept(new GreeterImpl(), new HeaderServerInterceptor()))
.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");
CustomHeaderServer.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(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");
HelloJsonServer.this.stop();
System.err.println("*** server shut down");
}
});
}
void run() throws Exception {
// Port 0 means that the operating system will pick an available port to use.
Server server = ServerBuilder.forPort(0).addService(new GreeterGrpc.GreeterImplBase() {
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
responseObserver.onError(Status.INTERNAL
.withDescription("Eggplant Xerxes Crybaby Overbite Narwhal").asRuntimeException());
}
}).build().start();
channel =
ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext().build();
blockingCall();
futureCallDirect();
futureCallCallback();
asyncCall();
advancedAsyncCall();
channel.shutdown();
server.shutdown();
channel.awaitTermination(1, TimeUnit.SECONDS);
server.awaitTermination();
}
void run() throws Exception {
Server server = ServerBuilder.forPort(0).addService(new GreeterGrpc.GreeterImplBase() {
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
Metadata trailers = new Metadata();
trailers.put(DEBUG_INFO_TRAILER_KEY, DEBUG_INFO);
responseObserver.onError(Status.INTERNAL.withDescription(DEBUG_DESC)
.asRuntimeException(trailers));
}
}).build().start();
channel =
ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext().build();
blockingCall();
futureCallDirect();
futureCallCallback();
asyncCall();
advancedAsyncCall();
channel.shutdown();
server.shutdown();
channel.awaitTermination(1, TimeUnit.SECONDS);
server.awaitTermination();
}
@Bean(name = "grpcInternalConfigurator")
public Consumer<ServerBuilder<?>> configurator(GRpcServerBuilderConfigurer configurer){
return serverBuilder -> {
if(grpcServerProperties.isEnabled()){
Optional.ofNullable(grpcServerProperties.getSecurity())
.ifPresent(s->{
boolean setupSecurity = Optional.ofNullable(s.getCertChain()).isPresent();
if(setupSecurity != Optional.ofNullable(s.getPrivateKey()).isPresent() ){
throw new BeanCreationException("Both gRPC TLS 'certChain' and 'privateKey' should be configured. One of them is null. ");
}
if(setupSecurity) {
try {
serverBuilder.useTransportSecurity(s.getCertChain().getInputStream(),
s.getPrivateKey().getInputStream()
);
} catch (IOException e) {
throw new BeanCreationException("Failed to setup security", e);
}
}
});
}
configurer.configure(serverBuilder);
};
}
private void start() throws IOException {
server = ServerBuilder.forPort(port)
.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");
HelloWorldServer2.this.stop();
System.err.println("*** server shut down");
}
});
}
private void start() throws IOException {
server = ServerBuilder.forPort(PORT)
.addService(ServerInterceptors.intercept(new GreeterImpl(), new HeaderServerInterceptor()))
.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");
CustomHeaderServer.this.stop();
System.err.println("*** server shut down");
}
});
}
private void start() throws IOException {
server = ServerBuilder.forPort(port)
.addService(new GreeterImpl())
.intercept(new JwtServerInterceptor()) // add the JwtServerInterceptor
.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");
AuthServer.this.stop();
System.err.println("*** server shut down");
}
});
}
void run() throws Exception {
Server server = ServerBuilder.forPort(0).addService(new GreeterGrpc.GreeterImplBase() {
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
Metadata trailers = new Metadata();
trailers.put(DEBUG_INFO_TRAILER_KEY, DEBUG_INFO);
responseObserver.onError(Status.INTERNAL.withDescription(DEBUG_DESC)
.asRuntimeException(trailers));
}
}).build().start();
channel =
ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext().build();
blockingCall();
futureCallDirect();
futureCallCallback();
asyncCall();
advancedAsyncCall();
channel.shutdown();
server.shutdown();
channel.awaitTermination(1, TimeUnit.SECONDS);
server.awaitTermination();
}
public void start() throws IOException {
serviceImpl = new GreeterImpl();
server = ServerBuilder.forPort(port)
.addService(serviceImpl)
.build()
.start();
logger.info("CommonServiceSecondServer start...");
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");
CommonServiceSecondServer.this.stop();
System.err.println("*** CommonServiceFirstServer shut down");
}
});
}
public void start() throws IOException {
server = ServerBuilder.forPort(port)
.addService(new PersonNameImpl())
.addService(new PersonAgeImpl())
.addService(new PersonSalaryImpl())
.addService(new PersonInfoImpl())
.build()
.start();
logger.info("PersonServiceServer start...");
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");
PersonServiceServer.this.stop();
System.err.println("*** PersonServiceServer shut down");
}
});
}
private void start() throws IOException {
/* The port on which the server should run */
int port = 50051;
server = ServerBuilder.forPort(port)
.addService(new GreeterImpl())
.build()
.start();
logger.info("Server started, listening on " + port);
DecimalFormat df = new DecimalFormat("#%");
logger.info("Responding as UNAVAILABLE to " + df.format(UNAVAILABLE_PERCENTAGE) + " requests");
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");
try {
RetryingHelloWorldServer.this.stop();
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
System.err.println("*** server shut down");
}
});
}
public void start() throws IOException {
server = ServerBuilder.forPort(port)
.addService(new GreeterImpl2(port))
.build()
.start();
logger.info("ConsumerTestServer start...");
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");
ConsumerTestServer.this.stop();
System.err.println("*** ConsumerTestServer shut down");
}
});
}
public void start() throws IOException {
server = ServerBuilder.forPort(port)
.addService(new EventServerImpl())
.build()
.start();
log.info("EventGrpcServer start, port: " + port);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
log.info("Shutting down EventGrpcServer since JVM is shutting down");
EventGrpcServer.this.stop();
log.error("EventGrpcServer 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");
}
});
}
private Server createServer() {
// distributed locks
LockManager lockManager = new LockManager();
JanusGraphFactory janusGraphFactory = new JanusGraphFactory(serverConfig);
HadoopGraphFactory hadoopGraphFactory = new HadoopGraphFactory(serverConfig);
Integer storagePort = serverConfig.getProperty(ConfigKey.STORAGE_PORT);
String storageHostname = serverConfig.getProperty(ConfigKey.STORAGE_HOSTNAME);
// CQL cluster used by KeyspaceManager to fetch all existing keyspaces
CqlSession cqlSession = CqlSession.builder()
.addContactPoint(new InetSocketAddress(storageHostname, storagePort))
.withLocalDatacenter("datacenter1")
.build();
sessionFactory = new SessionFactory(lockManager, janusGraphFactory, hadoopGraphFactory, serverConfig);
keyspaceManager = new KeyspaceManager(cqlSession, janusGraphFactory, sessionFactory);
OpenRequest requestOpener = new ServerOpenRequest(sessionFactory);
io.grpc.Server serverRPC = ServerBuilder.forPort(grpcPort)
.addService(new SessionService(requestOpener))
.addService(new KeyspaceService(keyspaceManager))
.build();
return ServerFactory.createServer(serverRPC);
}
/**
* 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;
}
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(new GoalStateProvisionerImpl())
.build()
.start();
Logger logger = LoggerFactory.getLogger();
logger.log(Level.INFO, "GoalStateProvisionerServer : Server started, listening on ");
logger.log(Level.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.
logger.log(Level.SEVERE, "*** shutting down gRPC server since JVM is shutting down");
GoalStateProvisionerServer.this.stop();
logger.log(Level.SEVERE, "*** server shut down");
}
});
}
private void start() throws IOException {
/* The port on which the server should run */
int port = 50051;
server = ServerBuilder.forPort(port)
.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");
try {
CompressingHelloWorldServerPerMethod.this.stop();
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
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(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");
try {
HelloJsonServer.this.stop();
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
System.err.println("*** server shut down");
}
});
}
/**
* 启动服务
* @throws Exception 异常
*/
public void start() throws Exception{
int port = grpcProperties.getPort();
if (serverInterceptor != null){
server = ServerBuilder.forPort(port).addService(ServerInterceptors.intercept(commonService, serverInterceptor)).build().start();
}else {
Class clazz = grpcProperties.getServerInterceptor();
if (clazz == null){
server = ServerBuilder.forPort(port).addService(commonService).build().start();
}else {
server = ServerBuilder.forPort(port).addService(ServerInterceptors.intercept(commonService, (ServerInterceptor) clazz.newInstance())).build().start();
}
}
log.info("gRPC Server started, listening on port " + server.getPort());
startDaemonAwaitThread();
}
/**
* 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();
}
@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();
}
public void start() throws IOException {
/* The port on which the server should run */
int port = 50075;
if (server == null || server.isShutdown() || server.isTerminated()) {
server = ServerBuilder.forPort(port)
.addService(new TestServiceImpl())
.addService(new JwtAuthTestServiceGrpcImpl())
.addService(new ThrottlingTestServiceGrpcImpl())
.build().start();
}
log.info("Server started, listening on " + port);
}
@Autowired
public ExternalRpcServer(PredictionService predictionService)
{
logger.info("Initializing RPC server...");
this.predictionService = predictionService;
ServerBuilder<?> serverBuilder = ServerBuilder.forPort(port);
server = serverBuilder.addService(ServerInterceptors.intercept(this, this)).build();
}