20 Ekim 2021 Çarşamba

gRPC Unary Service

Giriş
- Cevap olarak döndürülecek nesneyi Builder yardımıyla yaratırız.
- Daha sonra responseObserver.onNext() çağrısına cevap nesnesini geçeriz.
- En son olarak ta responseObserver.OnCompleted() çağrısını yaparız

Örnek
Elimizde şöyle bir servis olsun
import com.grpc.hello.grpc.HelloGrpc.HelloImplBase;
import com.grpc.hello.grpc.HelloReply;
import com.grpc.hello.grpc.HelloReply.Builder;
import com.grpc.hello.grpc.HelloRequest;

import io.grpc.stub.StreamObserver;

public class HelloService extends HelloImplBase {
  @Override
  public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
    Builder response = HelloReply.newBuilder();

    String caller = request.getName();
    String greet = "Hello " + caller;
    response.setMessage(greet);
    responseObserver.onNext(response.build());
    responseObserver.onCompleted();
  }
}
Örnek
Şöyle yaparız
@Override
public void hello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {

  String greeting = ...;

  HelloResponse response = HelloResponse.newBuilder()
    .setGreeting(greeting)
    .build();

  responseObserver.onNext(response);
  responseObserver.onCompleted();
}
Örnek - Hata Durumu
Şöye yaparız. Burada io.grpc.StatusException döndürülüyor
public class ProductService extends ProductServiceGrpc.ProductServiceImplBase { private final ProductRepository productRepository; public ProductService() { this.productRepository = new ProductRepository(); } @Override public void getProduct( GetProductRequest request, StreamObserver<GetProductResponse> responseObserver) { var productId = request.getProductId(); //Fetch Product information from repository Optional<Product> optionalProduct = productRepository.get(productId); if (optionalProduct.isPresent()) { var product = optionalProduct.get(); //If found build response var productResponse = Service.Product.newBuilder() .setName(product.getName()) .setDescription(product.getDescription()) .setPrice(product.getPrice()) .build(); var getProductResponse = GetProductResponse.newBuilder() .setProduct(productResponse).build(); responseObserver.onNext(getProductResponse); responseObserver.onCompleted(); } else { responseObserver.onError(new StatusException(Status.NOT_FOUND)); } log.info("Finished calling Product API service.."); } }

Hiç yorum yok:

Yorum Gönder