下面列出了怎么用io.grpc.examples.helloworld.HelloReply的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();
}
}
/**
* 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 {
// 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();
}
@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);
}
@Before
public void setUp() throws Exception {
GreeterImplBase greeterImplBase =
new GreeterImplBase() {
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
responseObserver.onNext(HelloReply.getDefaultInstance());
responseObserver.onCompleted();
}
};
// Generate a unique in-process server name.
String serverName = InProcessServerBuilder.generateName();
// Create a server, add service, start, and register for automatic graceful shutdown.
grpcCleanup.register(InProcessServerBuilder.forName(serverName).directExecutor()
.addService(ServerInterceptors.intercept(greeterImplBase, new HeaderServerInterceptor()))
.build().start());
// Create a client channel and register for automatic graceful shutdown.
channel =
grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build());
}
/**
* Say hello to server in a blocking unary call.
*/
public void greet(String name) {
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
HelloReply response = null;
StatusRuntimeException statusRuntimeException = null;
try {
response = blockingStub.sayHello(request);
} catch (StatusRuntimeException e) {
failedRpcs.incrementAndGet();
statusRuntimeException = e;
}
totalRpcs.incrementAndGet();
if (statusRuntimeException == null) {
logger.log(Level.INFO,"Greeting: {0}", new Object[]{response.getMessage()});
} else {
logger.log(Level.INFO,"RPC failed: {0}", new Object[]{statusRuntimeException.getStatus()});
}
}
@Test
public void requestWithNoCacheOptionSkipsCache() {
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse,
safeGreeterSayHelloMethod,
CallOptions.DEFAULT.withOption(SafeMethodCachingInterceptor.NO_CACHE_CALL_OPTION, true),
message);
HelloReply reply3 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertNotEquals(reply1, reply2);
assertSame(reply1, reply3);
}
@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 responseNoCacheDirective_notCached() throws Exception {
cacheControlDirectives.add("no-cache");
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertNotEquals(reply1, reply2);
assertNotEquals(reply1, reply2);
Truth.assertThat(cache.internalCache).isEmpty();
Truth.assertThat(cache.removedKeys).isEmpty();
}
@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);
}
@Test
public void cacheHit_doesNotResetExpiration() 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);
sleepAtLeast(1001);
HelloReply reply3 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertSame(reply1, reply2);
assertNotEquals(reply1, reply3);
Truth.assertThat(cache.internalCache).hasSize(1);
Truth.assertThat(cache.removedKeys).hasSize(1);
}
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 {
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();
}
@Before
public void setUp() throws Exception {
GreeterImplBase greeterImplBase =
new GreeterImplBase() {
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
responseObserver.onNext(HelloReply.getDefaultInstance());
responseObserver.onCompleted();
}
};
// Generate a unique in-process server name.
String serverName = InProcessServerBuilder.generateName();
// Create a server, add service, start, and register for automatic graceful shutdown.
grpcCleanup.register(InProcessServerBuilder.forName(serverName).directExecutor()
.addService(ServerInterceptors.intercept(greeterImplBase, new HeaderServerInterceptor()))
.build().start());
// Create a client channel and register for automatic graceful shutdown.
channel =
grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build());
}
@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 =
OkHttpChannelBuilder.forAddress(host, port)
.transportExecutor(new NetworkTaggingExecutor(0xFDD))
.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 cacheHit_doesNotResetExpiration() 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);
sleepAtLeast(1001);
HelloReply reply3 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertSame(reply1, reply2);
assertNotEquals(reply1, reply3);
Truth.assertThat(cache.internalCache).hasSize(1);
Truth.assertThat(cache.removedKeys).hasSize(1);
}
@Test
public void responseNoCacheDirective_notCached() throws Exception {
cacheControlDirectives.add("no-cache");
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertNotEquals(reply1, reply2);
assertNotEquals(reply1, reply2);
Truth.assertThat(cache.internalCache).isEmpty();
Truth.assertThat(cache.removedKeys).isEmpty();
}
/** Say hello to server. */
public void greet(String name) {
logger.info("Will try to greet " + name + " ...");
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
HelloReply response;
try {
// This enables compression for requests. Independent of this setting, servers choose whether
// to compress responses.
response = blockingStub.withCompression("gzip").sayHello(request);
} catch (StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return;
}
logger.info("Greeting: " + response.getMessage());
}
@Test
public void invalidResponseMaxAge_usesDefault() throws Exception {
SafeMethodCachingInterceptor interceptorWithCustomMaxAge =
SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache, 1);
channelToUse = ClientInterceptors.intercept(baseChannel, interceptorWithCustomMaxAge);
cacheControlDirectives.add("max-age=-10");
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertEquals(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));
}
/** Say hello to server. */
public void greet(String name) {
logger.info("Will try to greet " + name + " ...");
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
HelloReply response;
try {
response = blockingStub.sayHello(request);
} catch (StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return;
}
logger.info("Greeting: " + response.getMessage());
}
/**
* 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(trailers.containsKey(DEBUG_INFO_TRAILER_KEY));
try {
Verify.verify(trailers.get(DEBUG_INFO_TRAILER_KEY).equals(DEBUG_INFO));
} catch (IllegalArgumentException e) {
throw new VerifyException(e);
}
latch.countDown();
}
}, new Metadata());
call.sendMessage(HelloRequest.newBuilder().build());
call.halfClose();
if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
throw new RuntimeException("timeout!");
}
}
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!");
}
}
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
TraceContext currentTraceContext = tracing != null ? tracing.currentTraceContext().get() : null;
if (req.getName().equals("bad")) {
responseObserver.onError(new IllegalArgumentException("bad"));
return;
}
if (req.getName().equals("testerror")) {
throw new RuntimeException("testerror");
}
String message = currentTraceContext != null ? currentTraceContext.traceIdString() : "";
HelloReply reply = HelloReply.newBuilder().setMessage(message).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
@Test
public void sayHello_fixedHostname() throws Exception {
grpcCleanup.register(
InProcessServerBuilder.forName("hostname")
.directExecutor().addService(new HostnameGreeter("me")).build().start());
HelloReply reply =
blockingStub.sayHello(HelloRequest.newBuilder().setName("you").build());
assertEquals("Hello you, from me", reply.getMessage());
}
@Test public void setsErrorTag_onCanceledFuture() {
server.enqueueDelay(TimeUnit.SECONDS.toMillis(1));
ListenableFuture<HelloReply> resp = GreeterGrpc.newFutureStub(client).sayHello(HELLO_REQUEST);
assumeTrue("lost race on cancel", resp.cancel(true));
MutableSpan span = testSpanHandler.takeRemoteSpanWithErrorTag(CLIENT, "CANCELLED");
assertThat(span.tags().get("grpc.status_code")).isEqualTo("CANCELLED");
}
/**
* 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(trailers.containsKey(DEBUG_INFO_TRAILER_KEY));
try {
Verify.verify(trailers.get(DEBUG_INFO_TRAILER_KEY).equals(DEBUG_INFO));
} catch (IllegalArgumentException e) {
throw new VerifyException(e);
}
latch.countDown();
}
}, new Metadata());
call.sendMessage(HelloRequest.newBuilder().build());
call.halfClose();
if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
throw new RuntimeException("timeout!");
}
}
@Test
public void requestWithOnlyIfCachedOption_usesCache() {
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse,
safeGreeterSayHelloMethod,
CallOptions.DEFAULT.withOption(
SafeMethodCachingInterceptor.ONLY_IF_CACHED_CALL_OPTION, true),
message);
assertSame(reply1, reply2);
}
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!");
}
}
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
HelloReply reply = HelloReply.newBuilder()
.setMessage("Hello " + req.getName() + ", from " + serverName)
.build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}