gRPC - 客户端调用
gRPC 客户端支持两种类型的客户端调用,即客户端如何调用服务器。以下是两种方式:
阻塞式客户端调用
异步客户端调用
在本章中,我们将逐一查看它们。
阻塞式客户端调用
gRPC 支持阻塞式客户端调用。这意味着,一旦客户端向服务发出调用,客户端将不会继续执行其余代码,直到从服务器收到响应。请注意,对于单向调用和服务器流式调用,阻塞式客户端调用是可能的。
请注意,对于单向调用和服务器流式调用,阻塞式客户端调用是可能的。
这是一个单向阻塞式客户端调用的示例。
示例
package com.tp.bookstore; import io.grpc.Channel; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import com.tp.bookstore.BookStoreOuterClass.Book; import com.tp.bookstore.BookStoreOuterClass.BookSearch; import com.tp.greeting.GreeterGrpc; import com.tp.greeting.Greeting.ServerOutput; import com.tp.greeting.Greeting.ClientInput; public class BookStoreClientUnaryBlocking { private static final Logger logger = Logger.getLogger(BookStoreClientUnaryBlocking.class.getName()); private final BookStoreGrpc.BookStoreBlockingStubblockingStub; public BookStoreClientUnaryBlocking(Channel channel) { blockingStub = BookStoreGrpc.newBlockingStub(channel); } public void getBook(String bookName) { logger.info("Querying for book with title: " + bookName); BookSearch request = BookSearch.newBuilder().setName(bookName).build(); Book response; try { response = blockingStub.first(request); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus()); return; } logger.info("Got following book from server: " + response); } public static void main(String[] args) throws Exception { String bookName = args[0]; String serverAddress = "localhost:50051"; ManagedChannel channel = ManagedChannelBuilder.forTarget(serverAddress) .usePlaintext() .build(); try { BookStoreClientUnaryBlocking client = new BookStoreClientUnaryBlocking(channel); client.getBook(bookName); } finally { channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); } } }
在上面的示例中,我们有:
public BookStoreClientUnaryBlocking(Channel channel) { blockingStub = BookStoreGrpc.newBlockingStub(channel); }
这意味着我们将使用阻塞式 RPC 调用。
然后,我们有:
BookSearch request = BookSearch.newBuilder().setName(bookName).build(); Book response; response = blockingStub.first(request);
在这里,我们使用 **blockingStub** 调用 RPC **method first()** 来获取图书详情。
类似地,对于服务器流式,我们可以使用阻塞式存根:
logger.info("Querying for book with author: " + author); BookSearch request = BookSearch.newBuilder().setAuthor(author).build(); Iterator<Book> response; try { response = blockingStub.searchByAuthor(request); while(response.hasNext()) { logger.info("Found book: " + response.next()); }
我们在这里调用 RPC 方法 **searchByAuthor** 方法,并迭代响应,直到服务器流结束。
非阻塞式客户端调用
gRPC 支持非阻塞式客户端调用。这意味着当客户端向服务发出调用时,它不需要等待服务器响应。为了处理服务器响应,客户端可以简单地传入观察者,该观察者决定在收到响应时该做什么。请注意,对于单向调用和流式调用,非阻塞式客户端调用都是可能的。但是,我们将特别关注服务器流式调用的情况,以便将其与阻塞式调用进行比较。
请注意,对于单向调用和流式调用,非阻塞式客户端调用都是可能的。但是,我们将特别关注服务器流式调用的情况,以便将其与阻塞式调用进行比较。
这是一个服务器流式非阻塞式客户端调用的示例
示例
package com.tp.bookstore; import io.grpc.Channel; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; import java.util.Iterator; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import com.tp.bookstore.BookStoreOuterClass.Book; import com.tp.bookstore.BookStoreOuterClass.BookSearch; import com.tp.greeting.GreeterGrpc; import com.tp.greeting.Greeting.ServerOutput; import com.tp.greeting.Greeting.ClientInput; public class BookStoreClientServerStreamingNonBlocking { private static final Logger logger = Logger.getLogger(BookStoreClientServerStreamingNonBlocking.class.getName()); private final BookStoreGrpc.BookStoreStub nonBlockingStub; public BookStoreClientServerStreamingNonBlocking(Channelchannel) { nonBlockingStub = BookStoreGrpc.newStub(channel); } public StreamObserver<Book> getServerResponseObserver(){ StreamObserver<Book> observer = new StreamObserver<Book>(){ @Override public void onNext(Book book) { logger.info("Server returned following book: " +book); } @Override public void onError(Throwable t) { logger.info("Error while reading response fromServer: " + t); } @Override public void onCompleted() { logger.info("Server returned following book: " + book); } }; return observer; } public void getBook(String author) { logger.info("Querying for book with author: " + author); BookSearch request = BookSearch.newBuilder().setAuthor(author).build(); try { nonBlockingStub.searchByAuthor(request,getServerResponseObserver()); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC failed: {0}",e.getStatus()); return; } } public static void main(String[] args) throws Exception { String authorName = args[0]; String serverAddress = "localhost:50051"; ManagedChannel channel =ManagedChannelBuilder.forTarget(serverAddress) .usePlaintext() .build(); try { BookStoreClientServerStreamingNonBlocking client = new BookStoreClientServerStreamingNonBlocking(channel); client.getBook(authorName); } finally { channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); } } }
正如我们在上面的示例中看到的:
public BookStoreClientUnaryNonBlocking(Channel channel) { nonBlockingStub = BookStoreGrpc.newStub(channel); }
它定义了存根是非阻塞式的。类似地,以下代码用于处理我们从服务器接收到的响应。一旦服务器发送响应,我们就记录输出。
public StreamObserver<Book> getServerResponseObserver(){ StreamObserver<Book> observer = new StreamObserver<Book>(){ .... .... return observer; }
以下 gRPC 调用是非阻塞式调用。
logger.info("Querying for book with author: " + author); BookSearch request = BookSearch.newBuilder().setAuthor(author).build(); try { nonBlockingStub.searchByAuthor(request, getServerResponseObserver()); }
这就是我们确保客户端不需要等到服务器完成 **searchByAuthor** 执行的方式。这将由流观察者对象在服务器返回 Book 对象时直接处理。