下面列出了怎么用io.grpc.examples.helloworld.HelloRequest的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
@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);
}
}
/**
* 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();
}
@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()});
}
}
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;
}
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
HelloRequest.DateTime reqDateTime = req.getDateTime();
int i = 0;
try {
i = Integer.parseInt(reqDateTime.getTime());
} catch (Exception e) {
//TODO: handle exception
}
LocalDateTime dt = LocalDateTime.now();
String dtStr = dt.format(datetimeFormatter[i % datetimeFormatter.length]);
HelloRequest.DateTime rplyDateTime = HelloRequest.DateTime.newBuilder(reqDateTime)
.setDate(dtStr).build();
HelloReply reply = HelloReply.newBuilder()
.setMessage("Hello " + req.getName())
.setDateTime(rplyDateTime)
.build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("spring/dubbo-demo-consumer.xml");
context.start();
/**
* greeter sample
*/
System.out.println("-------- Start simple unary call test -------- ");
ReactorDubboGreeterGrpc.IReactorGreeter greeter = (ReactorDubboGreeterGrpc.IReactorGreeter) context.getBean("greeter");
greeter
.sayHello(HelloRequest.newBuilder().setName("world!").build())
.subscribe(reply -> System.out.println("Result: " + reply));
System.out.println("-------- End simple unary call test -------- \n\n\n");
System.in.read();
}
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("spring/dubbo-demo-consumer.xml");
context.start();
/**
* greeter sample
*/
System.out.println("-------- Start simple unary call test -------- ");
RxDubboGreeterGrpc.IRxGreeter greeter = (RxDubboGreeterGrpc.IRxGreeter) context.getBean("greeter");
greeter
.sayHello(HelloRequest.newBuilder().setName("world!").build())
.subscribe(reply -> System.out.println("Result: " + reply));
System.out.println("-------- End simple unary call test -------- \n\n\n");
System.in.read();
}
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 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!");
}
}
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();
}
}
/**
* 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());
}
/** 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());
}
/**
* A simple client method that like {@link io.grpc.examples.helloworld.HelloWorldClient}.
*/
private 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());
}
void asyncCall() {
GreeterStub stub = GreeterGrpc.newStub(channel);
HelloRequest request = HelloRequest.newBuilder().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) {
verifyErrorReply(t);
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) {
// get client id added to context by interceptor
String clientId = Constant.CLIENT_ID_CONTEXT_KEY.get();
logger.info("Processing request from " + clientId);
HelloReply reply = HelloReply.newBuilder().setMessage("Hello, " + req.getName()).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
/**
* 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 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.
}
}
@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 blockingCall() {
GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
try {
stub.sayHello(HelloRequest.newBuilder().build());
} catch (Exception e) {
verifyErrorReply(e);
}
}
void futureCallCallback() {
GreeterFutureStub stub = GreeterGrpc.newFutureStub(channel);
ListenableFuture<HelloReply> response =
stub.sayHello(HelloRequest.newBuilder().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) {
verifyErrorReply(t);
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().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) {
verifyErrorReply(t);
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!");
}
}
@Test
public void serverHeaderDeliveredToClient() {
class SpyingClientInterceptor implements ClientInterceptor {
ClientCall.Listener<?> spyListener;
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
spyListener = responseListener =
mock(ClientCall.Listener.class, delegatesTo(responseListener));
super.start(responseListener, headers);
}
};
}
}
SpyingClientInterceptor clientInterceptor = new SpyingClientInterceptor();
GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(channel)
.withInterceptors(clientInterceptor);
ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);
blockingStub.sayHello(HelloRequest.getDefaultInstance());
assertNotNull(clientInterceptor.spyListener);
verify(clientInterceptor.spyListener).onHeaders(metadataCaptor.capture());
assertEquals(
"customRespondValue",
metadataCaptor.getValue().get(HeaderServerInterceptor.CUSTOM_HEADER_KEY));
}
@Test
public void clientHeaderDeliveredToServer() throws Exception {
// 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(new GreeterImplBase() {}, mockServerInterceptor))
.build().start());
// Create a client channel and register for automatic graceful shutdown.
ManagedChannel channel = grpcCleanup.register(
InProcessChannelBuilder.forName(serverName).directExecutor().build());
GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(
ClientInterceptors.intercept(channel, new HeaderClientInterceptor()));
ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);
try {
blockingStub.sayHello(HelloRequest.getDefaultInstance());
fail();
} catch (StatusRuntimeException expected) {
// expected because the method is not implemented at server side
}
verify(mockServerInterceptor).interceptCall(
Matchers.<ServerCall<HelloRequest, HelloReply>>any(),
metadataCaptor.capture(),
Matchers.<ServerCallHandler<HelloRequest, HelloReply>>any());
assertEquals(
"customRequestValue",
metadataCaptor.getValue().get(HeaderClientInterceptor.CUSTOM_HEADER_KEY));
}
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> plainResponseObserver) {
ServerCallStreamObserver<HelloReply> responseObserver =
(ServerCallStreamObserver<HelloReply>) plainResponseObserver;
/* This line by itself enables compression for the response */
responseObserver.setCompression("gzip");
HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}