本文整理汇总了Java中io.grpc.Server类的典型用法代码示例。如果您正苦于以下问题:Java Server类的具体用法?Java Server怎么用?Java Server使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Server类属于io.grpc包,在下文中一共展示了Server类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: newInstance
import io.grpc.Server; //导入依赖的package包/类
@Override
public Lifecycle newInstance(KernelContext kernelContext, final Dependencies dependencies) throws Throwable {
return new LifecycleAdapter() {
private Server server;
@Override
public void start() throws Throwable {
server = ServerBuilder.forPort(9999).addService(new Neo4jGRPCService(dependencies.getGraphDatabaseService())).build();
server.start();
System.out.println("Started gRPC Server.");
}
@Override
public void shutdown() throws Throwable {
server.shutdown();
}
};
}
示例2: close
import io.grpc.Server; //导入依赖的package包/类
/**
* 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;
}
}
}
示例3: start
import io.grpc.Server; //导入依赖的package包/类
/**
* Start Netty Grpc Server.
*
* @return Server gRPC Server
* @throws IOException - when something went wrong starting the grpc server
*/
final Server start() throws IOException {
final int port = 8080;
log.info("Starting grpc server on port '{}'...", port);
final Server server =
NettyServerBuilder
.forPort(port)
.addService(productReadService)
.addService(productUpdateService)
.addService(ServerInterceptors.intercept(echoService, serviceInterceptor))
.build();
server.start();
log.info("grpc (port={}) server started successfully.", port);
return server;
}
示例4: stopSendingWhenClusterIsDown
import io.grpc.Server; //导入依赖的package包/类
@Test
public void stopSendingWhenClusterIsDown() throws Exception {
servers.values().forEach(Server::shutdownNow);
messageSender.onConnected();
Thread thread = new Thread(() -> messageSender.send(event));
thread.start();
// we don't want to keep sending on cluster down
await().atMost(2, SECONDS).until(() -> thread.isAlive() && thread.getState().equals(WAITING));
assertThat(eventsMap.get(8080).isEmpty(), is(true));
assertThat(eventsMap.get(8090).isEmpty(), is(true));
startServerOnPort(8080);
startServerOnPort(8090);
await().atMost(2, SECONDS).until(() -> connected.get(8080).size() == 2 || connected.get(8090).size() == 2);
await().atMost(2, SECONDS).until(() -> eventsMap.get(8080).size() == 1 || eventsMap.get(8090).size() == 1);
}
示例5: startDoesNotStartServerWithoutServices
import io.grpc.Server; //导入依赖的package包/类
@Test
public void startDoesNotStartServerWithoutServices() throws Exception {
final int port = ThreadLocalRandom.current().nextInt(1000, 10000);
final long shutdownWaitTimeInMillis = ThreadLocalRandom.current().nextLong(1000, 10000);
final ApplicationContext applicationContext = mock(ApplicationContext.class);
final Server server = mock(Server.class, new TriesToReturnSelf());
final GrpcServerFactory factory = mock(GrpcServerFactory.class);
when(server.getPort()).thenReturn(port);
// Configure application context to contain no gRPC services.
when(applicationContext.getBeansWithAnnotation(eq(GrpcService.class))).thenReturn(ImmutableMap.of());
GrpcServerHost runner = new GrpcServerHost(port, shutdownWaitTimeInMillis, factory);
runner.setApplicationContext(applicationContext);
assertThatThrownBy(runner::start).isInstanceOf(IOException.class);
// Make sure the server builder was not used.
verify(factory, never()).buildServerForServices(anyInt(), any());
assertThat(runner.server()).isNull();
}
示例6: getPortReturnsServerPortForRunningServer
import io.grpc.Server; //导入依赖的package包/类
@Test
public void getPortReturnsServerPortForRunningServer() throws Exception {
final int configPort = ThreadLocalRandom.current().nextInt(1000, 2000);
final int serverPort = ThreadLocalRandom.current().nextInt(2000, 3000);
final int serviceCount = ThreadLocalRandom.current().nextInt(5, 10);
final long shutdownWaitTimeInMillis = ThreadLocalRandom.current().nextLong(1000, 10000);
final ApplicationContext applicationContext = mock(ApplicationContext.class);
final Server server = mock(Server.class, new TriesToReturnSelf());
final GrpcServerFactory factory = (p, s) -> server;
final Map<String, Object> services = IntStream.range(0, serviceCount)
.mapToObj(i -> mock(BindableService.class))
.collect(Collectors.toMap(s -> UUID.randomUUID().toString(), s -> s));
when(applicationContext.getBeansWithAnnotation(eq(GrpcService.class))).thenReturn(services);
when(server.getPort()).thenReturn(serverPort);
GrpcServerHost runner = new GrpcServerHost(configPort, shutdownWaitTimeInMillis, factory);
runner.setApplicationContext(applicationContext);
runner.start();
assertThat(runner.getPort()).isEqualTo(serverPort);
}
示例7: shutdownGracefully
import io.grpc.Server; //导入依赖的package包/类
/**
* Attempt to {@link Server#shutdown()} the {@link Server} gracefully. If the max wait time is exceeded, give up and
* perform a hard {@link Server#shutdownNow()}.
*
* @param server the server to be shutdown
* @param timeout the max amount of time to wait for graceful shutdown to occur
* @param unit the time unit denominating the shutdown timeout
* @return the given server
* @throws InterruptedException if waiting for termination is interrupted
*/
public static Server shutdownGracefully(Server server, long timeout, TimeUnit unit) throws InterruptedException {
Preconditions.checkNotNull(server, "server");
Preconditions.checkArgument(timeout > 0, "timeout must be greater than 0");
Preconditions.checkNotNull(unit, "unit");
server.shutdown();
try {
server.awaitTermination(timeout, unit);
} finally {
server.shutdownNow();
}
return server;
}
示例8: shutdownGracefullyPropagatesAwaitInterrupt
import io.grpc.Server; //导入依赖的package包/类
@Test
public void shutdownGracefullyPropagatesAwaitInterrupt() throws Exception {
final Server server = mock(Server.class);
final long maxWaitTimeInMillis = ThreadLocalRandom.current().nextLong(1, 10000);
final InterruptedException interruptedException = new InterruptedException();
when(server.awaitTermination(anyLong(), any())).thenThrow(interruptedException);
assertThatThrownBy(() -> Servers.shutdownGracefully(server, maxWaitTimeInMillis))
.isSameAs(interruptedException);
InOrder inOrder = Mockito.inOrder(server);
inOrder.verify(server).shutdown();
inOrder.verify(server).awaitTermination(eq(maxWaitTimeInMillis), eq(TimeUnit.MILLISECONDS));
inOrder.verify(server).shutdownNow();
}
示例9: serverRunsAndRespondsCorrectly
import io.grpc.Server; //导入依赖的package包/类
@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();
}
示例10: main
import io.grpc.Server; //导入依赖的package包/类
public static void main(String[] args) throws InterruptedException {
Server server=ServerBuilder.forPort(Config.getLocalPortProvider())
.addService(new AddService())
.build();
try {
server.start();
ProviderBootstrap.init();
server.awaitTermination();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
示例11: createAndStart
import io.grpc.Server; //导入依赖的package包/类
/**
* Tries a few times to start a server. If this returns, the server has been started. Throws
* {@link RuntimeException} on failure.
*/
public static TestServer createAndStart(Optional<SslContext> sslContext) {
RecordingTestService recordingTestService = new RecordingTestService(
UNARY_SERVER_RESPONSE,
STREAMING_SERVER_RESPONSE,
CLIENT_STREAMING_SERVER_RESPONSE,
BIDI_SERVER_RESPONSE);
Random random = new Random();
for (int i = 0; i < NUM_SERVER_START_TRIES; ++i) {
int port = random.nextInt(MAX_SERVER_PORT - MIN_SERVER_PORT + 1) + MIN_SERVER_PORT;
try {
Server server = tryStartServer(port, recordingTestService, sslContext);
// If we got this far, we have successfully started the server.
return new TestServer(server, port, recordingTestService);
} catch (IOException e) {
// The random port might have been in use, try again...
continue;
}
}
// If we got to here, we didn't manage to start a server.
throw new RuntimeException("Unable to start server after " + NUM_SERVER_START_TRIES + " tries");
}
示例12: main
import io.grpc.Server; //导入依赖的package包/类
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();
}
示例13: createAndStartGrpcServer
import io.grpc.Server; //导入依赖的package包/类
protected void createAndStartGrpcServer() throws IOException {
Server localServer = this.server;
if (localServer == null) {
this.server = factory.createServer();
this.server.start();
logger.info("gRPC Server started, listening on address: "
+ this.factory.getAddress() + ", port: " + this.factory.getPort());
Thread awaitThread = new Thread(
"container-" + (serverCounter.incrementAndGet())) {
@Override
public void run() {
try {
GrpcServerLifecycle.this.server.awaitTermination();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
};
awaitThread.setDaemon(false);
awaitThread.start();
}
}
示例14: run
import io.grpc.Server; //导入依赖的package包/类
/** Equivalent of "main", but non-static. */
public void run(String[] args) throws Exception {
final Server server = newServer();
server.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
System.out.println("Server shutting down");
server.shutdown();
server.awaitTermination(5, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
示例15: start
import io.grpc.Server; //导入依赖的package包/类
private AsyncFuture<Void> start() throws IOException {
final Server server = NettyServerBuilder
.forAddress(address)
.addService(bindService())
.maxMessageSize(maxFrameSize)
.bossEventLoopGroup(bossGroup)
.workerEventLoopGroup(workerGroup)
.build();
return async.call(() -> {
server.start();
this.server.set(server);
return null;
}).directTransform(v -> {
final InetSocketAddress localAddress = extractInetSocketAddress(server);
bindFuture.resolve(localAddress);
return null;
});
}