下面列出了怎么用io.grpc.examples.helloworld.GreeterGrpc的API类实例代码及写法,或者点击链接到github查看源代码。
private void run(String[] args) throws InterruptedException {
parseArgs(args);
ExecutorService executor = Executors.newFixedThreadPool(1);
ManagedChannel channel = AltsChannelBuilder.forTarget(serverAddress).executor(executor).build();
try {
GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
HelloReply resp = stub.sayHello(HelloRequest.newBuilder().setName("Waldo").build());
logger.log(Level.INFO, "Got {0}", resp);
} finally {
channel.shutdown();
channel.awaitTermination(1, TimeUnit.SECONDS);
// Wait until the channel has terminated, since tasks can be queued after the channel is
// shutdown.
executor.shutdown();
}
}
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();
}
/**
* This is more advanced and does not make use of the stub. You should not normally need to do
* this, but here is how you would.
*/
void advancedAsyncCall() {
ClientCall<HelloRequest, HelloReply> call =
channel.newCall(GreeterGrpc.getSayHelloMethod(), CallOptions.DEFAULT);
final CountDownLatch latch = new CountDownLatch(1);
call.start(new ClientCall.Listener<HelloReply>() {
@Override
public void onClose(Status status, Metadata trailers) {
Verify.verify(status.getCode() == Status.Code.INTERNAL);
Verify.verify(status.getDescription().contains("Narwhal"));
// Cause is not transmitted over the wire.
latch.countDown();
}
}, new Metadata());
call.sendMessage(HelloRequest.newBuilder().setName("Marge").build());
call.halfClose();
if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
throw new RuntimeException("timeout!");
}
}
@Override
protected String doInBackground(String... params) {
String host = params[0];
String message = params[1];
String portStr = params[2];
int port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr);
try {
channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build();
GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
HelloRequest request = HelloRequest.newBuilder().setName(message).build();
HelloReply reply = stub.sayHello(request);
return reply.getMessage();
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
return String.format("Failed... : %n%s", sw);
}
}
@Test
public void afterResponseMaxAge_cacheEntryInvalidated() throws Exception {
cacheControlDirectives.add("max-age=1");
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertSame(reply1, reply2);
// Wait for cache entry to expire
sleepAtLeast(1001);
assertNotEquals(
reply1,
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message));
Truth.assertThat(cache.removedKeys).hasSize(1);
assertEquals(
new SafeMethodCachingInterceptor.Key(
GreeterGrpc.getSayHelloMethod().getFullMethodName(), message),
cache.removedKeys.get(0));
}
Set<String> getThreadsUsedFor100Requests() throws InterruptedException, ExecutionException, TimeoutException {
int requestNo = 100;
List<Callable<String>> calls = new ArrayList<>();
for (int i = 0; i < requestNo; i++) {
calls.add(() -> {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9000)
.usePlaintext()
.build();
HelloReply reply = GreeterGrpc.newBlockingStub(channel)
.sayHello(HelloRequest.newBuilder().setName("foo").build());
channel.shutdownNow();
return reply.getMessage();
});
}
List<Future<String>> results = Executors.newFixedThreadPool(requestNo)
.invokeAll(calls);
Set<String> threads = new HashSet<>();
for (Future<String> result : results) {
threads.add(result.get(10, TimeUnit.SECONDS));
}
return threads;
}
private void run(String[] args) throws InterruptedException {
parseArgs(args);
ExecutorService executor = Executors.newFixedThreadPool(1);
ManagedChannel channel = AltsChannelBuilder.forTarget(serverAddress).executor(executor).build();
try {
GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
HelloReply resp = stub.sayHello(HelloRequest.newBuilder().setName("Waldo").build());
logger.log(Level.INFO, "Got {0}", resp);
} finally {
channel.shutdown();
channel.awaitTermination(1, TimeUnit.SECONDS);
// Wait until the channel has terminated, since tasks can be queued after the channel is
// shutdown.
executor.shutdown();
}
}
@Test public void deprecated_clientParserTestStreamingResponse() {
closeClient(client);
grpcTracing = grpcTracing.toBuilder().clientParser(new GrpcClientParser() {
int receiveCount = 0;
@Override protected <M> void onMessageReceived(M message, SpanCustomizer span) {
span.tag("grpc.message_received." + receiveCount++, message.toString());
}
}).build();
client = newClient();
Iterator<HelloReply> replies = GreeterGrpc.newBlockingStub(client)
.sayHelloWithManyReplies(HelloRequest.newBuilder().setName("this is dog").build());
assertThat(replies).toIterable().hasSize(10);
// all response messages are tagged to the same span
assertThat(testSpanHandler.takeRemoteSpan(CLIENT).tags()).hasSize(10);
}
/**
* Construct client connecting to HelloWorld server at {@code host:port}.
*/
public RetryingHelloWorldClient(String host, int port, boolean enableRetries) {
ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress(host, port)
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
// needing certificates.
.usePlaintext();
if (enableRetries) {
Map<String, ?> serviceConfig = getRetryingServiceConfig();
logger.info("Client started with retrying configuration: " + serviceConfig);
channelBuilder.defaultServiceConfig(serviceConfig).enableRetry();
}
channel = channelBuilder.build();
blockingStub = GreeterGrpc.newBlockingStub(channel);
this.enableRetries = enableRetries;
}
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();
}
/**
* This is more advanced and does not make use of the stub. You should not normally need to do
* this, but here is how you would.
*/
void advancedAsyncCall() {
ClientCall<HelloRequest, HelloReply> call =
channel.newCall(GreeterGrpc.getSayHelloMethod(), CallOptions.DEFAULT);
final CountDownLatch latch = new CountDownLatch(1);
call.start(new ClientCall.Listener<HelloReply>() {
@Override
public void onClose(Status status, Metadata trailers) {
Verify.verify(status.getCode() == Status.Code.INTERNAL);
Verify.verify(status.getDescription().contains("Narwhal"));
// Cause is not transmitted over the wire.
latch.countDown();
}
}, new Metadata());
call.sendMessage(HelloRequest.newBuilder().setName("Marge").build());
call.halfClose();
if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
throw new RuntimeException("timeout!");
}
}
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();
}
/**
* This ensures that response callbacks run in the invocation context, not the client one. This
* allows async chaining to appear caused by the parent, not by the most recent client. Otherwise,
* we would see a client span child of a client span, which could be confused with duplicate
* instrumentation and affect dependency link counts.
*/
@Test public void callbackContextIsFromInvocationTime() {
AssertableCallback<HelloReply> callback = new AssertableCallback<>();
// Capture the current trace context when onSuccess or onError occur
AtomicReference<TraceContext> invocationContext = new AtomicReference<>();
callback.setListener(() -> invocationContext.set(currentTraceContext.get()));
TraceContext parent = newTraceContext(SamplingFlags.SAMPLED);
try (Scope scope = currentTraceContext.newScope(parent)) {
GreeterGrpc.newStub(client).sayHello(HELLO_REQUEST, new StreamObserverAdapter(callback));
}
callback.join(); // ensures listener ran
assertThat(invocationContext.get()).isSameAs(parent);
assertChildOf(testSpanHandler.takeRemoteSpan(CLIENT), parent);
}
/** Construct client connecting to HelloWorld server at {@code host:port}. */
public HedgingHelloWorldClient(String host, int port, boolean hedging) {
Map<String, ?> hedgingServiceConfig =
new Gson()
.fromJson(
new JsonReader(
new InputStreamReader(
HedgingHelloWorldClient.class.getResourceAsStream(
"hedging_service_config.json"),
UTF_8)),
Map.class);
ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress(host, port)
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
// needing certificates.
.usePlaintext();
if (hedging) {
channelBuilder.defaultServiceConfig(hedgingServiceConfig).enableRetry();
}
channel = channelBuilder.build();
blockingStub = GreeterGrpc.newBlockingStub(channel);
this.hedging = hedging;
}
@Override
protected String doInBackground(String... params) {
String host = params[0];
String message = params[1];
String portStr = params[2];
int port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr);
try {
channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build();
GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
HelloRequest request = HelloRequest.newBuilder().setName(message).build();
HelloReply reply = stub.sayHello(request);
return reply.getMessage();
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
return String.format("Failed... : %n%s", sw);
}
}
@Test
public void afterResponseMaxAge_cacheEntryInvalidated() throws Exception {
cacheControlDirectives.add("max-age=1");
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertSame(reply1, reply2);
// Wait for cache entry to expire
sleepAtLeast(1001);
assertNotEquals(
reply1,
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message));
Truth.assertThat(cache.removedKeys).hasSize(1);
assertEquals(
new SafeMethodCachingInterceptor.Key(
GreeterGrpc.getSayHelloMethod().getFullMethodName(), message),
cache.removedKeys.get(0));
}
/**
* NOTE: for this to work, the tracing interceptor must be last (so that it executes first)
*
* <p>Also notice that we are only making the current context available in the request side.
*/
@Test public void currentSpanVisibleToUserInterceptors() throws IOException {
AtomicReference<TraceContext> fromUserInterceptor = new AtomicReference<>();
init(new ServerInterceptor() {
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call,
Metadata headers, ServerCallHandler<ReqT, RespT> next) {
fromUserInterceptor.set(tracing.currentTraceContext().get());
return next.startCall(call, headers);
}
});
GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST);
assertThat(fromUserInterceptor.get())
.isNotNull();
testSpanHandler.takeRemoteSpan(Span.Kind.SERVER);
}
@Test public void userInterceptor_throwsOnHalfClose() {
closeClient(client);
client = newClient(new ClientInterceptor() {
@Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions,
Channel channel) {
ClientCall<ReqT, RespT> call = channel.newCall(methodDescriptor, callOptions);
return new SimpleForwardingClientCall<ReqT, RespT>(call) {
@Override public void halfClose() {
throw new IllegalStateException("I'm a bad interceptor.");
}
};
}
}, grpcTracing.newClientInterceptor());
assertThatThrownBy(() -> GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST))
.isInstanceOf(IllegalStateException.class);
testSpanHandler.takeRemoteSpanWithErrorMessage(CLIENT, "I'm a bad interceptor.");
}
@Test public void serverParserTestWithStreamingResponse() throws IOException {
grpcTracing = grpcTracing.toBuilder().serverParser(new GrpcServerParser() {
int responsesSent = 0;
@Override protected <M> void onMessageSent(M message, SpanCustomizer span) {
span.tag("grpc.message_sent." + responsesSent++, message.toString());
}
}).build();
init();
Iterator<HelloReply> replies = GreeterGrpc.newBlockingStub(client)
.sayHelloWithManyReplies(HELLO_REQUEST);
assertThat(replies).toIterable().hasSize(10);
// all response messages are tagged to the same span
assertThat(testSpanHandler.takeRemoteSpan(Span.Kind.SERVER).tags()).hasSize(10);
}
@Test public void userInterceptor_throwsOnSendMessage() throws IOException {
init(new ServerInterceptor() {
@Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call, Metadata metadata, ServerCallHandler<ReqT, RespT> next) {
return next.startCall(new SimpleForwardingServerCall<ReqT, RespT>(call) {
@Override public void sendMessage(RespT message) {
throw new IllegalStateException("I'm a bad interceptor.");
}
}, metadata);
}
});
assertThatThrownBy(() -> GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST))
.isInstanceOf(StatusRuntimeException.class);
testSpanHandler.takeRemoteSpanWithErrorMessage(Span.Kind.SERVER, "I'm a bad interceptor.");
}
@Test public void userInterceptor_throwsOnOnHalfClose() throws IOException {
init(new ServerInterceptor() {
@Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call, Metadata metadata, ServerCallHandler<ReqT, RespT> next) {
return new SimpleForwardingServerCallListener<ReqT>(next.startCall(call, metadata)) {
@Override public void onHalfClose() {
throw new IllegalStateException("I'm a bad interceptor.");
}
};
}
});
assertThatThrownBy(() -> GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST))
.isInstanceOf(StatusRuntimeException.class);
testSpanHandler.takeRemoteSpanWithErrorMessage(Span.Kind.SERVER, "I'm a bad interceptor.");
}
@Test public void customSampler() throws IOException {
RpcTracing rpcTracing = RpcTracing.newBuilder(tracing).serverSampler(RpcRuleSampler.newBuilder()
.putRule(methodEquals("SayHelloWithManyReplies"), NEVER_SAMPLE)
.putRule(serviceEquals("helloworld.greeter"), ALWAYS_SAMPLE)
.build()).build();
grpcTracing = GrpcTracing.create(rpcTracing);
init();
// unsampled
// NOTE: An iterator request is lazy: invoking the iterator invokes the request
GreeterGrpc.newBlockingStub(client).sayHelloWithManyReplies(HELLO_REQUEST).hasNext();
// sampled
GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST);
assertThat(testSpanHandler.takeRemoteSpan(Span.Kind.SERVER).name())
.isEqualTo("helloworld.Greeter/SayHello");
// @After will also check that sayHelloWithManyReplies was not sampled
}
@Test public void userInterceptor_throwsOnStart() {
closeClient(client);
client = newClient(new ClientInterceptor() {
@Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions,
Channel channel) {
ClientCall<ReqT, RespT> call = channel.newCall(methodDescriptor, callOptions);
return new SimpleForwardingClientCall<ReqT, RespT>(call) {
@Override public void start(Listener<RespT> responseListener, Metadata headers) {
throw new IllegalStateException("I'm a bad interceptor.");
}
};
}
}, grpcTracing.newClientInterceptor());
assertThatThrownBy(() -> GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST))
.isInstanceOf(IllegalStateException.class);
testSpanHandler.takeRemoteSpanWithErrorMessage(CLIENT, "I'm a bad interceptor.");
}
/** Construct client connecting to HelloWorld server at {@code host:port}. */
public CompressingHelloWorldClient(String host, int port) {
channel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext()
.build();
blockingStub = GreeterGrpc.newBlockingStub(channel);
}
/**
* A custom client.
*/
private CustomHeaderClient(String host, int port) {
originChannel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext()
.build();
ClientInterceptor interceptor = new HeaderClientInterceptor();
Channel channel = ClientInterceptors.intercept(originChannel, interceptor);
blockingStub = GreeterGrpc.newBlockingStub(channel);
}
@Override
public ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition
.builder(GreeterGrpc.getServiceDescriptor().getName())
.addMethod(HelloJsonClient.HelloJsonStub.METHOD_SAY_HELLO,
asyncUnaryCall(
new UnaryMethod<HelloRequest, HelloReply>() {
@Override
public void invoke(
HelloRequest request, StreamObserver<HelloReply> responseObserver) {
sayHello(request, responseObserver);
}
}))
.build();
}
void blockingCall() {
GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
try {
stub.sayHello(HelloRequest.newBuilder().setName("Bart").build());
} catch (Exception e) {
Status status = Status.fromThrowable(e);
Verify.verify(status.getCode() == Status.Code.INTERNAL);
Verify.verify(status.getDescription().contains("Eggplant"));
// Cause is not transmitted over the wire.
}
}
void futureCallCallback() {
GreeterFutureStub stub = GreeterGrpc.newFutureStub(channel);
ListenableFuture<HelloReply> response =
stub.sayHello(HelloRequest.newBuilder().setName("Maggie").build());
final CountDownLatch latch = new CountDownLatch(1);
Futures.addCallback(
response,
new FutureCallback<HelloReply>() {
@Override
public void onSuccess(@Nullable HelloReply result) {
// Won't be called, since the server in this example always fails.
}
@Override
public void onFailure(Throwable t) {
Status status = Status.fromThrowable(t);
Verify.verify(status.getCode() == Status.Code.INTERNAL);
Verify.verify(status.getDescription().contains("Crybaby"));
// Cause is not transmitted over the wire..
latch.countDown();
}
},
directExecutor());
if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
throw new RuntimeException("timeout!");
}
}
void asyncCall() {
GreeterStub stub = GreeterGrpc.newStub(channel);
HelloRequest request = HelloRequest.newBuilder().setName("Homer").build();
final CountDownLatch latch = new CountDownLatch(1);
StreamObserver<HelloReply> responseObserver = new StreamObserver<HelloReply>() {
@Override
public void onNext(HelloReply value) {
// Won't be called.
}
@Override
public void onError(Throwable t) {
Status status = Status.fromThrowable(t);
Verify.verify(status.getCode() == Status.Code.INTERNAL);
Verify.verify(status.getDescription().contains("Overbite"));
// Cause is not transmitted over the wire..
latch.countDown();
}
@Override
public void onCompleted() {
// Won't be called, since the server in this example always fails.
}
};
stub.sayHello(request, responseObserver);
if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
throw new RuntimeException("timeout!");
}
}
void blockingCall() {
GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
try {
stub.sayHello(HelloRequest.newBuilder().build());
} catch (Exception e) {
verifyErrorReply(e);
}
}