下面列出了io.grpc.Server#awaitTermination ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void stop() throws InterruptedException {
Server s = server;
if (s == null) {
throw new IllegalStateException("gRPC Listener Server is already stopped");
}
server = null;
s.shutdown();
if (s.awaitTermination(1, TimeUnit.SECONDS)) {
log.debug("gRPC Listener Server stopped");
return;
}
s.shutdownNow();
if (s.awaitTermination(1, TimeUnit.SECONDS)) {
return;
}
throw new RuntimeException("Unable to shutdown gRPC Listener Server");
}
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();
}
public static void main(String[] arg) {
try {
Server server = ServerBuilder.forPort(8080)
.addService(new EmployeeService())
.build();
System.out.println("Starting gRPC Server Service ...");
server.start();
System.out.println("Server has started at port: 8080");
System.out.println("Following services are available: ");
server.getServices().stream()
.forEach(
s -> System.out.println("Service Name: " + s.getServiceDescriptor().getName())
);
server.awaitTermination();
} catch (Exception e) {
e.printStackTrace();
}
}
private void stopServer() throws InterruptedException {
Server s = server;
if (s == null) {
throw new IllegalStateException("Already stopped");
}
server = null;
s.shutdown();
if (s.awaitTermination(1, TimeUnit.SECONDS)) {
return;
}
s.shutdownNow();
if (s.awaitTermination(1, TimeUnit.SECONDS)) {
return;
}
throw new RuntimeException("Unable to shutdown server");
}
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();
}
/**
* Shutdown the gRPC {@link Server} when this object is closed.
*/
@Override
public void close() throws Exception {
final Server server = server();
if (server != null) {
server.shutdown();
try {
// TODO: Maybe we should catch the InterruptedException from this?
server.awaitTermination(shutdownWaitTimeInMillis, TimeUnit.MILLISECONDS);
} finally {
server.shutdownNow();
this.server = null;
}
}
}
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();
}
public static void main(String[] args) throws IOException, InterruptedException {
RxMetricsServiceGrpc.MetricsServiceImplBase service = new RxMetricsServiceGrpc.MetricsServiceImplBase() {
@Override
public Single<Streaming.Average> collect(Flowable<Streaming.Metric> request) {
return request.map(m -> m.getMetric())
.map(m -> new State(m, 1))
.reduce((a, b) -> new State(a.sum + b.sum, a.count + b.count))
.map(s -> Streaming.Average.newBuilder().setVal(s.sum / s.count).build())
.toSingle();
}
};
Server server = ServerBuilder.forPort(8080)
.addService(service)
.build();
server.start();
server.awaitTermination();
}
@Override
public void execute() throws Exception {
StaticScanner staticScanner = new StaticScanner();
staticScanner.addStepsToRegistry();
Server server;
boolean multithreading = false;
int stream = 1;
String streamValue = System.getenv(STREAMS_COUNT_ENV);
if (streamValue != null && !streamValue.isEmpty()) {
stream = Integer.parseInt(streamValue);
multithreading = true;
}
MessageProcessorFactory messageProcessorFactory = new MessageProcessorFactory(staticScanner);
RunnerServiceHandler runnerServiceHandler = new RunnerServiceHandler(messageProcessorFactory, multithreading, stream);
server = ServerBuilder.forPort(0).addService(runnerServiceHandler).executor((Executor) Runnable::run).build();
runnerServiceHandler.addServer(server);
server.start();
int port = server.getPort();
Logger.info("Listening on port:" + port);
server.awaitTermination();
System.exit(0);
}
@Override
public Void call() throws Exception {
OzoneConfiguration ozoneConfiguration = createOzoneConfiguration();
CsiConfig csiConfig = ozoneConfiguration.getObject(CsiConfig.class);
OzoneClient rpcClient = OzoneClientFactory.getRpcClient(ozoneConfiguration);
EpollEventLoopGroup group = new EpollEventLoopGroup();
if (csiConfig.getVolumeOwner().isEmpty()) {
throw new IllegalArgumentException(
"ozone.csi.owner is not set. You should set this configuration "
+ "variable to define which user should own all the created "
+ "buckets.");
}
Server server =
NettyServerBuilder
.forAddress(new DomainSocketAddress(csiConfig.getSocketPath()))
.channelType(EpollServerDomainSocketChannel.class)
.workerEventLoopGroup(group)
.bossEventLoopGroup(group)
.addService(new IdentitiyService())
.addService(new ControllerService(rpcClient,
csiConfig.getDefaultVolumeSize()))
.addService(new NodeService(csiConfig))
.build();
server.start();
server.awaitTermination();
rpcClient.close();
return null;
}
/**
* The following method shuts down an {@code Server} in two
* phases, first by calling {@code shutdown} to reject incoming tasks,
* and then calling {@code shutdownNow}, if necessary, to cancel any
* lingering tasks.
*/
public static boolean shutdownAndAwaitTermination(final Server server, final long timeoutMillis) {
if (server == null) {
return true;
}
// disable new tasks from being submitted
server.shutdown();
final TimeUnit unit = TimeUnit.MILLISECONDS;
final long phaseOne = timeoutMillis / 5;
try {
// wait a while for existing tasks to terminate
if (server.awaitTermination(phaseOne, unit)) {
return true;
}
server.shutdownNow();
// wait a while for tasks to respond to being cancelled
if (server.awaitTermination(timeoutMillis - phaseOne, unit)) {
return true;
}
LOG.warn("Fail to shutdown grpc server: {}.", server);
} catch (final InterruptedException e) {
// (Re-)cancel if current thread also interrupted
server.shutdownNow();
// preserve interrupt status
Thread.currentThread().interrupt();
}
return false;
}
static public void main(String[] args) throws IOException, InterruptedException {
Server server = ServerBuilder.forPort(8080)
.addService(new EchoServiceImpl()).build();
System.out.println("Starting server...");
server.start();
System.out.println("Server started!");
server.awaitTermination();
}
static public void main(String [] args) throws IOException, InterruptedException {
Server server = ServerBuilder.forPort(8080)
.addService(new GreetingServiceImpl()).build();
System.out.println("Starting server...");
server.start();
System.out.println("Server started!");
server.awaitTermination();
}
public static void main(String[] args) throws Exception {
Server server = NettyServerBuilder
.forPort(PORT)
.addService(new ContinuousBackpressureDemoServer())
.flowControlWindow(NettyServerBuilder.DEFAULT_FLOW_CONTROL_WINDOW)
.build()
.start();
System.out.println("Listening on port 9999");
server.awaitTermination();
}
@Test
public void serverRunsAndRespondsCorrectly() throws ExecutionException,
IOException,
InterruptedException,
TimeoutException {
final String name = UUID.randomUUID().toString();
Server server = ServerBuilder.forPort(9999)
.addService(new GreeterImpl())
.build();
server.start();
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", server.getPort())
.usePlaintext(true)
.build();
GreeterGrpc8.GreeterCompletableFutureStub stub = GreeterGrpc8.newCompletableFutureStub(channel);
CompletableFuture<HelloResponse> response = stub.sayHello(HelloRequest.newBuilder().setName(name).build());
await().atMost(3, TimeUnit.SECONDS).until(() -> response.isDone() && response.get().getMessage().contains(name));
channel.shutdown();
channel.awaitTermination(1, TimeUnit.MINUTES);
channel.shutdownNow();
server.shutdown();
server.awaitTermination(1, TimeUnit.MINUTES);
server.shutdownNow();
}
/**
* main method (and init()) is not actually needed, but helpful for debugging
* purposes
*
* @param args
* @throws Exception
*/
public static void main(final String[] args) throws Exception {
init();
Server server = ServerBuilder.forPort(8080).addService(new PCSBasedOptimizerServiceImpl(evaluator, input)).build();
server.start();
server.awaitTermination();
}
/**
* 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();
}
public static void main(String[] args) throws Exception {
// Start the server
Server server = ServerBuilder.forPort(8888).addService(new GrpcServer()).build().start();
server.awaitTermination();
}
public static void main(String[] args) throws InterruptedException, IOException {
Server server = ServerBuilder.forPort(9090).addService(new ChatServiceImpl()).build();
server.start();
server.awaitTermination();
}