gRPC-Server&Client

博客以官方RouteGuideService为例,介绍了RouteGuideService类需继承.proto文件生成的抽象类。还涉及Simple RPC、Server - side streaming RPC等内容,包括启动gRPC服务器、创建客户端以及调用服务方法等信息技术相关操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用官方的RouteGuideService例子 ,RouteGuideService类需要extends from .proto文件生成的RouteGuideGrpc.RouteGuideImplBase抽象类

private static class RouteGuideService extends RouteGuideGrpc.RouteGuideImplBase {
...
}

Simple RPC

@Override
public void getFeature(Point request, StreamObserver<Feature> responseObserver) {
  responseObserver.onNext(yourHandleMethod(request));
  responseObserver.onCompleted();
}
/**
getFeature() takes two parameters:
    Point: the request
    StreamObserver<Feature>: a response observer, which is a special interface for the server to call with its response.
**/
//方法解释
/**
We use the response observer’s onNext() method to return the Feature.
We use the response observer’s onCompleted() method to specify that we’ve finished dealing with the RPC.
**/

Server-side streaming RPC

@Override
public void listFeatures(Rectangle request, StreamObserver<Feature> responseObserver) {
  int left = min(request.getLo().getLongitude(), request.getHi().getLongitude());
  int right = max(request.getLo().getLongitude(), request.getHi().getLongitude());
  int top = max(request.getLo().getLatitude(), request.getHi().getLatitude());
  int bottom = min(request.getLo().getLatitude(), request.getHi().getLatitude());

  for (Feature feature : features) {
    if (!RouteGuideUtil.exists(feature)) {
      continue;
    }

    int lat = feature.getLocation().getLatitude();
    int lon = feature.getLocation().getLongitude();
    if (lon >= left && lon <= right && lat >= bottom && lat <= top) {
      responseObserver.onNext(feature);
    }
  }
  responseObserver.onCompleted();
}
/**
Like the simple RPC, this method gets a request object (the Rectangle in which our client wants to find Features) and a StreamObserver response observer.

This time, we get as many Feature objects as we need to return to the client (in this case, we select them from the service’s feature collection based on whether they’re inside our request Rectangle), and write them each in turn to the response observer using its onNext() method. Finally, as in our simple RPC, we use the response observer’s onCompleted() method to tell gRPC that we’ve finished writing responses.
**/

Starting the Server

       once we've implemented all our methods, we also need to start up a gRPC server so that clients can acutally use our service.The following snippet shows how we do this for our RouteGuide service:

public RouteGuideServer(int port, URL featureFile) throws IOException {
  this(ServerBuilder.forPort(port), port, RouteGuideUtil.parseFeatures(featureFile));
}

/** Create a RouteGuide server using serverBuilder as a base and features as data. */
public RouteGuideServer(ServerBuilder<?> serverBuilder, int port, Collection<Feature> features) {
  this.port = port;
  server = serverBuilder.addService(new RouteGuideService(features))
      .build();
}
...
public void start() throws IOException {
  server.start();
  logger.info("Server started, listening on " + port);
 ...
}

/**
1.Specify the address and port we want to use to listen for client requests using the builder’s forPort() method.
2.Create an instance of our service implementation class RouteGuideService and pass it to the builder’s addService() method.
3.Call build() and start() on the builder to create and start an RPC server for our service.
**/

Creating the client

    First we need to create a gRPC channel for our stub, specifying the server address and port we want to connect to:

    

public RouteGuideClient(String host, int port) {
  this(ManagedChannelBuilder.forAddress(host, port).usePlaintext());
}

/** Construct client for accessing RouteGuide server using the existing channel. */
public RouteGuideClient(ManagedChannelBuilder<?> channelBuilder) {
  channel = channelBuilder.build();
  blockingStub = RouteGuideGrpc.newBlockingStub(channel);
  asyncStub = RouteGuideGrpc.newStub(channel);
}

Calling service methods

  -Simple gRPC

Point request = Point.newBuilder().setLatitude(lat).setLongitude(lon).build();
Feature feature;
try {
  feature = blockingStub.getFeature(request);
} catch (StatusRuntimeException e) {
  logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
  return;
}

     

//未完 。。。后续有时间更新

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值