gRPC etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
gRPC etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

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.."); } }

gRPC Server

Başlatma
- Önce bir tane io.grpc.Server nesnesi yaratmak gerekir. nesneyi yaratmak  için io.grpc.ServerBuilder veya io.grpc.netty.NettyServerBuilder kullanılır
- Servislerimizi addService() çağrısı ile ekleriz. 
- server.start() çağrısı ile server başlatılır
- En son server.awaitTermination() çağrısı ile beklenir

Durdurma
-shutdown() çağrısı server durdurma işlemi başlatılır. awaitTermination() ile durdurma işleminin bitmesi beklenir.


gRPC Gradle Plugin

Örnek
build.gradle dosyasında şöyle yaparız. Üretilen gRPC dosyalarını projeye dahil etmek için sourceSets bloğu kullanılır
plugins {
  id 'java'
  id "com.google.protobuf" version "0.8.12"
}

dependencies {
  //gRPC dependencies
  implementation 'com.google.protobuf:protobuf-java:3.17.3'
  implementation 'io.grpc:grpc-all:1.40.1'
  implementation 'javax.annotation:javax.annotation-api:1.3.2'
  ...
}

sourceSets {
  main {
    java {
      srcDirs 'build/generated/source/proto/main/grpc'
      srcDirs 'build/generated/source/proto/main/java'
    }
  }
}

protobuf {
  protoc {
    artifact = 'com.google.protobuf:protoc:3.12.4'
  }
  plugins {
    grpc {
      artifact = 'io.grpc:protoc-gen-grpc-java:1.31.0'
    }
  }
  generateProtoTasks {
    all()*.plugins {
      grpc {}
    }
  }
}

gRPC Unary

Örnek
Elimizde şöyle bir proto dosyası olsun
syntax = "proto3";
package dev.techdozo.product.api;

service ProductService {
  // A simple RPC.
  // returns Product for a given id
  rpc GetProduct(GetProductRequest) returns (GetProductResponse);
}

message GetProductRequest {
  string product_id = 1;
}

message GetProductResponse {
  Product product = 1;
}

message Product {
  string name = 1;
  string description = 2;
  double price = 3;
}

7 Eylül 2021 Salı

gRPC Error Handling

Giriş
Açıklaması şöyle
By default, gRPC relies heavily on status code for error handling. 
Sunucu tarafından fırlatılan exception gRPC tarafından StatusRuntimeException'a çevrilir.

Örnek
Şöyle yaparız. Burada ServiceException kendi sınıfımız
import io.grpc.StatusRuntimeException;

//Client call
public Product getProduct(String productId) {
  Product product = null;
  try {
    var request = GetProductRequest.newBuilder().setProductId(productId).build();
    var productApiServiceBlockingStub = ProductServiceGrpc.newBlockingStub(managedChannel);
    var response = productApiServiceBlockingStub.getProduct(request);
    // Map to domain object
    product = ProductMapper.MAPPER.map(response);
  } catch (StatusRuntimeException error) {
    log.error("Error while calling product service, cause {}", error.getMessage());
    throw new ServiceException(error.getCause());
  }
  return product;
}
Ancak bir problem var. O da hata mesajının kaybolması. Çıktı olarak şunu alırız
io.grpc.StatusRuntimeException: UNKNOWN
Açıklaması şöyle
gRPC wraps our custom exception in StatusRuntimeException and swallows the error message and assigns a default status code UNKNOWN.
Bunu düzeltmek için sunucu tarafında şöyle yaparız. Bu sefer onError() metodunu çağırıyoruz.
//Server Product Service API
public void getProduct(
    GetProductRequest request, StreamObserver<GetProductResponse> responseObserver) {
  try {
    ...
    responseObserver.onNext(response);
    responseObserver.onCompleted();
  } catch (ResourceNotFoundException error) {
    var status = Status.NOT_FOUND.withDescription(error.getMessage()).withCause(error);
    responseObserver.onError(status.asException());
  }
}
İstemci tarafında çıktı olarak şunu alırız. 
Error while calling product service, cause NOT_FOUND: Product ID not found
Hata mesajı düzgün ancak hala exception içindeki getCause() null döner. Sebebinin açıklaması şöyle. Yani io.grpc.Status.withCause() çağrısı orijinal exception'ı göndermiyor.
Create a derived instance of Status with the given cause. However, the cause is not transmitted from server to client.
Şöyle yaparız. Bu sefer io.grpc.Metadata kullanılıyor
public void getProduct(
    GetProductRequest request, StreamObserver<GetProductResponse> responseObserver) {
  try {
    ...
    responseObserver.onNext(response);
    responseObserver.onCompleted();
  } catch (ResourceNotFoundException error) {
    Map<String, String> errorMetaData = error.getErrorMetaData();
    var metadata = new Metadata();    
    errorMetaData.entrySet().stream() 
        .forEach(
            entry ->
                metadata.put(
                    Metadata.Key.of(entry.getKey(), Metadata.ASCII_STRING_MARSHALLER),
                    entry.getValue()));
    var statusRuntimeException =
        Status.NOT_FOUND.withDescription(error.getMessage()).asRuntimeException(metadata); 
    responseObserver.onError(statusRuntimeException);
  }
}
İstemci tarafında şöyle yaparız
} catch (StatusRuntimeException error) {

  Metadata trailers = error.getTrailers();
  Set<String> keys = trailers.keys();

  for (String key : keys) {
    Metadata.Key<String> k = Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER);
    log.info("Received key {}, with value {}", k, trailers.get(k));
  }
}
İstemci tarafında çıktı olarak şunu alırız. 
Received key Key{name='resource_id'}, with value 32c29935-da42-4801-825a-ac410584c281 
Received key Key{name='content-type'}, with value application/grpc 
Received key Key{name='message'}, with value Product ID not found
- Bütün bunlarlar uğraşmak yerine Google Richer Error Model kullanılabilir.
- Ayrıca sunucu tarafında bir sürü exceptıon yakalayıp io.grpc.Status dönmek yerine io.grpc.ServerInterceptor arayüzünden kalıtıp ortak bir kod yazılabilir.
- Eğer Spring kullanıyorsak aynı şeyi şöyle yaparız
@GrpcAdvice
public class ExceptionHandler {

  @GrpcExceptionHandler(ResourceNotFoundException.class)
  public StatusRuntimeException handleResourceNotFoundException(ResourceNotFoundException
cause) {
    var errorMetaData = cause.getErrorMetaData();
    var errorInfo =
        ErrorInfo.newBuilder()
            .setReason("Resource not found")
            .setDomain("Product")
            .putAllMetadata(errorMetaData)
            .build();
    var status =
        com.google.rpc.Status.newBuilder()
            .setCode(Code.NOT_FOUND.getNumber())
            .setMessage("Resource not found")
            .addDetails(Any.pack(errorInfo))
            .build();
    return StatusProto.toStatusRuntimeException(status);
  }
}


25 Ağustos 2021 Çarşamba

gRPC Load Balancing

Giriş
Açıklaması şöyle.
There are two types of load balancing options available in gRPC — proxy and client-side.
1. Proxy load balancing
2. Client-side load balancing
Proxy load balancing
Bir gRPC servisi istekleri karşılar, diğer gRPC servislerine dağıtır. Açıklaması şöyle.
In Proxy load balancing, the client issues RPCs to a Load Balancer (LB) proxy. The LB distributes the RPC call to one of the available backend servers that implement the actual logic for serving the call. The LB keeps track of load on each backend and implements algorithms for distributing load fairly. The clients themselves do not know about the backend servers. Clients can be untrusted. This architecture is typically used for user-facing services where clients from open internet can connect to the servers
Client-side load balancing
gRPC istemcisi gRPC servislerini bilir ve isteği kendi uygun gördüğü birine gönderir. Açıklaması şöyle.
In Client-side load balancing, the client is aware of many backend servers and chooses one to use for each RPC. If the client wishes it can implement the load balancing algorithms based on load report from the server. For simple deployment, clients can round-robin requests between available servers.
Client-side load balancing ve Kubernetes
Açıklaması şöyle. Yani gRPC  bir Connection Pool kullansaydı ve bağlantıları arada bir kapatıp tekrar açsaydı sorun olmayacaktı. Ancak gRPC bağlantıyı hep açık tutmak üzere tasarlanmış. Çözüm Serve-side Connection Management kullanmak
gRPC is built on HTTP/2, and HTTP/2 is designed to maintain a long-living TCP connection where all requests can be active on the same connection at any point in time. It reduces the overhead of connection management. ... once the connection is established, there’s no more balancing to be done. All requests get pinned to original destinations pods, as shown below until a new DNS discovery happens (with headless service). And it won’t happen until at least one of the existing connections breaks.
Serve-side Connection Management
Örnek
Şöyle yaparız
grpc.KeepaliveParams(keepalive.ServerParameters{
  MaxConnectionAge:      time.Second * 30,  // THIS one does the trick
  MaxConnectionAgeGrace: time.Second * 10,
})
Açıklaması şöyle
MAX_CONNECTION_AGE to 30 seconds. This time period is long enough to have low-latency communication without an expensive and frequent connection establishment process. Also, it allows services to react relatively quickly to the existence of new pods so the traffic distribution will be balanced.

MAX_CONNECTION_AGE_GRACE to 10 seconds. Defines the maximum time for the connection to be kept alive for outstanding RPCs to complete.


25 Haziran 2021 Cuma

gRPC SpringBoot Service

Giriş
gRPC servisi SpringBoot içinde de kullanılabilir. grpc-spring-boot-starter kullanılır. Bir örnek burada
1. gRPC Servisi Spring Component olarak tanımlanır
2. Bu service kullanılmak istenilen yerde @GrpcClient anotasyonu ile koda dahil edilir

Örnek
Servisi Spring component yapmak için şöyle yaparız
import io.grpc.stub.StreamObserver;
import org.lognet.springboot.grpc.GRpcService;

@GRpcService
public class UserDetailsService extends
UserDetailsServiceGrpc.UserDetailsServiceImplBase {
...
}
metodları için şöyle yaparız. Burada hem Unary hem de Bi-Directional Stream görülebilir.
@Override
public void generateRandomUser(UserDetailsRequest request,
StreamObserver<UserDetailsResponse> responseObserver) {
  UserDetailsResponse output = UserDetailsResponse.newBuilder()...;
    .setCity(...)
    ...
    .build();
  responseObserver.onNext(output);
  responseObserver.onCompleted();
}

@Override
public StreamObserver<UserDetailsRequest> generateRandomUserStream(
StreamObserver<UserDetailsResponse> responseObserver) {
  return new StreamObserver<UserDetailsRequest>() {
    @Override
    public void onNext(UserDetailsRequest input) {
      UserDetailsResponse output = UserDetailsResponse.newBuilder()
.setCity(...)
        ...
        .build();
responseObserver.onNext(output);
    }
    @Override
    public void onError(Throwable throwable) {
    }
    @Override
    public void onCompleted() {
      responseObserver.onCompleted();
    }
  };
}
Bunu  generateRandomUser() metodunu teker teker çağırmak için şöyle yaparız
import net.devh.boot.grpc.client.inject.GrpcClient;
import reactor.core.publisher.Flux;
@Service
public class UserDetailsGrpcBlockingClient {

  @GrpcClient("UserDetailsService")
  UserDetailsServiceGrpc.UserDetailsServiceBlockingStub userDetailsServiceBlockingStub;

  public Flux<Object> getUserDetailsResponse(Integer range) {
    return
      Flux.range(1, range)
.map(i -> UserDetailsRequest.newBuilder()
                    .setCity(...)
            ...
            .build())
.map(i -> {
  UserDetailsResponse response = this.userDetailsServiceBlockingStub
.generateRandomUser(i);
  return (Object) Map.of(response.getId(), new UserDetails(response));
         })
       .subscribeOn(Schedulers.boundedElastic());
  }
}
stream olarak çağırmak için şöyle yaparız. Burada gRPC StreamObserver nesnesi Flux nesnesine çevriliyor.
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.client.inject.GrpcClient;
import reactor.core.publisher.DirectProcessor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import reactor.core.scheduler.Schedulers;

@Service
public class UserDetailsGrpcStreamClient {

  @GrpcClient("UserDetailsService")
  private UserDetailsServiceGrpc.UserDetailsServiceStub stub;

  public Flux<Object> generateUserStreamResponse(Integer range){
    DirectProcessor<Object> processor = DirectProcessor.create();
    StreamObserver<UserDetailsResponse> observer =
new StreamObserverImpl(processor.sink());
    StreamObserver<UserDetailsRequest> inputStreamObserver =
this.stub.generateRandomUserStream(observer);
    return Flux.range(1, range)
      .map(i -> UserDetailsRequest.newBuilder()
        .setCity(...)
        ...
        .build())
      .doOnNext(inputStreamObserver::onNext)
      .zipWith(processor, (a, b) -> b)
      .doOnComplete(inputStreamObserver::onCompleted)
      .subscribeOn(Schedulers.boundedElastic());
  }
}
Çevirmek için şöyle yaparız.
class StreamObserverImpl implements StreamObserver<UserDetailsResponse> {

  final FluxSink<Object> sink;

  public StreamObserverImpl(FluxSink<Object> sink) {
    this.sink = sink;
  }

  @Override
  public void onNext(UserDetailsResponse output) {
  this.sink.next(Map.of(output.getId(), new UserDetails(output)));
  }

  @Override
  public void onError(Throwable throwable) {
    this.sink.error(throwable);
  }

  @Override
  public void onCompleted() {
    this.sink.complete();
  }
}

8 Haziran 2021 Salı

gRPC Client

Giriş
- Önce bir tane io.grpc.ManagedChannel yaratılır. Açıklaması şöyle
ManagedChannelBuilder is an abstract class and there are concrete implementations like NettyChannelBuilder and OkHttpChannelBuilder. When you use an API like ManagedChannelBuilder.forTarget() or Grpc.newChannelBuilder() gRPC finds an appropriate concrete implementation based on your platform and returns it (normally OkHttp on Android; Netty otherwise).
Daha sonra bir sub yaratılır. Blocking ve Non-blocking olarak iki tane stub çeşidi var. Açıklaması şöyle
gRPC supports two types of client stubs:
1. blocking/synchronous stub: in this stub, the RPC call waits for the server to respond.
2. non-blocking/asynchronous stub: client makes non-blocking calls to the server, where the response is returned asynchronously.
Blocking Stub
- ManagedChannel kullanılarak MyService.newBlockingStub(channel) çağrısı ile bir stub yaratılır. Stub servis çağrılarını içerir. Bu servis çağrılarını kullanarak gRPC kullanılır

- İşimiz bitince channel().awaitTermination() çağrısıyla kanal kapatılır

Non-blocking Stub With Callback
ManagedChannel kullanılarak MyService.newStub(channel) çağrısı ile bir stub yaratılır. Stub'a StreamObserver arayüzünü gerçekleştiren bir tane callback takılır. Callback gRPC'nin kendi threadleri üzerinde gerçekleşir. Açıklaması şöyle
For the callback, gRPC uses a cached thread pool that creates new threads as needed but will reuse previously constructed threads when they are available. 
Eğer kendi threadlerimizi kullanmak istersek bunu ManagedChannel seviyesinde yapmak gerekir. Şöyle yaparız
var executorService = Executors.newFixedThreadPool(10); 
var managedChannel = ManagedChannelBuilder.forAddress(host,port).executor(executorService)
  .usePlaintext() .build();
Non-blocking Stub With Future
Şöyle yaparız
// Create a new future stub 
var productServiceFutureStub = ProductServiceGrpc.newFutureStub(managedChannel);

var productRequest = GetProductRequest.newBuilder().setProductId("apple-123").build(); 
ListenableFuture<GetProductResponse> listenableFuture = productServiceFutureStub
  .getProduct(productRequest); 
Futures.addCallback(listenableFuture, new ProductCallback(), fixedThreadPool);

//or if you want Runnable
listenableFuture.addListener(this::notifyListener, fixedThreadPool);
Örnek - Blocking Stub
Şöyle yaparız
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;

import io.octutorials.ocgrpc.Defs.Payload;
import io.octutorials.ocgrpc.FetchGrpc;

import com.google.protobuf.ByteString;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

public class TutorialClient {
  private final ManagedChannel channel;
  private final FetchGrpc.FetchBlockingStub stub;

  public TutorialClient(String serverHost, int serverPort) {
    this.channel = ManagedChannelBuilder.forAddress(serverHost, serverPort)
      .usePlaintext(true)
      .build();
    this.stub = FetchGrpc.newBlockingStub(this.channel);
  }

  public void shutdown() throws InterruptedException {
    this.channel.shutdown().awaitTermination(4, TimeUnit.SECONDS);
  }

  public String capitalize(String data) throws Exception {
    ByteString bs = ByteString.copyFrom(data.getBytes("UTF8"));
    Payload in = Payload.newBuilder().setData(bs).build();
    Payload out = this.stub.capitalize(in);
    return out.getData().toString("UTF8");
  }
}
Örnek - Blocking Stub
Şöyle yaparız
var productServiceBlockingStub = ProductServiceGrpc.newBlockingStub(managedChannel);
var productRequest = GetProductRequest.newBuilder().setProductId("apple-123").build(); var productResponse = productServiceBlockingStub.getProduct(productRequest);
Örnek - Non-blocking Stub
Şöyle yaparız
var productServiceAsyncStub = ProductServiceGrpc.newStub(managedChannel);
var productRequest = GetProductRequest.newBuilder().setProductId("apple-123").build(); productServiceAsyncStub.getProduct(productRequest, new ProductCallback()); class ProductCallback implements StreamObserver<GetProductResponse> { @Override public void onNext(GetProductResponse value) { log.info("Received product, {}", value); } @Override public void onError(Throwable cause) { log.error("Error occurred, cause {}", cause.getMessage()); } @Override public void onCompleted() { log.info("Completed"); } }
b

gRPC Service

Kendi Servisimiz
proto dosyasındaki Servisin ismi Foo olsun. Kod üretildikten sonra kendi servisimiz şu şekilde kalıtır. FooGrpc üretilen koda ait bir "naming convention"
FooImpl extends FooGrpc.FooImplBase {...}
Eğer cevap döneceksek şöyle yaparız
responseObserver.onNext();
responseObserver.onCompleted();
Eğer hata varsa şöyle yaparız
responseObserver.onError()
Veri Tipleri
Protobuf dosyasında bytes olarak tanımlı bir alanı String'e çevirmek için com.google.protobuf.ByteString kullanılır

Unary Service
gRPC Unary Service yazısına taşıdım

Örnek - Bi-Directional
Şöyle yaparız
@Override
public StreamObserver<UserDetailsRequest> generateRandomUserStream(
StreamObserver<UserDetailsResponse> responseObserver) {
  return new StreamObserver<UserDetailsRequest>() {
    @Override
    public void onNext(UserDetailsRequest input) {
      UserDetailsResponse output = ...;
      responseObserver.onNext(output);
    }
    @Override
    public void onError(Throwable throwable) {
      ...
    }
    @Override
    public void onCompleted() {
      responseObserver.onCompleted();
    }
  };
}

gRPC Maven Dependency

Giriş
- grpc-protobuf ve grpc-stub bağımlılığı kesin gerekiyor. 
- grpc-netty-shaded veya grpc-netty arasındaki farkı bilmiyorum
- Java 9 ve üstü için annotations-api gerekiyor.

Stub Bileşeni
Açıklaması şöyle. Kendi kodumuzu yazarken kullandığımız StreamObserver gibi sınıflar bu bileşenden geliyor.
The Stub layer is what is exposed to most developers and provides type-safe bindings to whatever datamodel/IDL/interface you are adapting. gRPC comes with a plugin to the protocol-buffers compiler that generates Stub interfaces out of .proto files, but bindings to other datamodel/IDL are easy and encouraged.
Transport Bileşeni
Açıklaması şöyle
gRPC comes with three Transport implementations:

- The Netty-based transport is the main transport implementation based on Netty. It is for both the client and the server.
- The OkHttp-based transport is a lightweight transport based on OkHttp. It is mainly for use on Android and is for client only.
- The in-process transport is for when a server is in the same process as the client. It is useful for testing, while also being safe for production use.
Örnek - java 9
Şu satırı dahil ederiz
<dependency>
<groupId>io.grpc</groupId> <artifactId>grpc-stub</artifactId> <version>${grpc.version}</version> </dependency> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-protobuf</artifactId> <version>${grpc.version}</version> </dependency> <dependency> <groupId>jakarta.annotation</groupId> <artifactId>jakarta.annotation-api</artifactId> <version>1.3.5</version> <optional>true</optional> </dependency>
Örnek
Şu satırı dahil ederiz. Burada önemli olan şey grpc-netty. grpc-netty sunucu başlatmak için gerekir.
<dependency>
  <groupId>com.google.protobuf</groupId>
  <artifactId>protobuf-java</artifactId>
  <version>3.6.1</version>
</dependency>
<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-netty</artifactId>
  <version>1.30.0</version>
</dependency>
<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-protobuf</artifactId>
  <version>1.30.0</version>
</dependency>
<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-stub</artifactId>
  <version>1.30.0</version>
</dependency>
Örnek
Şu satırı dahil ederiz
<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-netty-shaded</artifactId>
  <version>1.30.2</version>
</dependency>
<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-protobuf</artifactId>
  <version>1.30.2</version>
</dependency>
<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-stub</artifactId>
  <version>1.30.2</version>
</dependency>
<dependency>
<!-- necessary for Java 9+ --> <groupId>org.apache.tomcat</groupId> <artifactId>annotations-api</artifactId> <version>6.0.53</version> <scope>provided</scope> </dependency>

gRPC Protobuf Dosyası - Service Tanımlama

Giriş
Önce proto dosyaları hazırlanır. Daha sonra bu dosyalardan kod üretilir.

Üye alan tipi olarak int32, string, bool, bytes kullanılabilir. bytes byte[] anlamına gelir.

Örnek - Unary With Empty Return
Şöyle yaparız
rpc DeleteProduct(DeleteProductRequest) returns (google.protobuf.Empty);
Örnek - Unary
Şöyle yaparız
syntax = "proto3";

service SampleDataService {
  rpc GetSampleData (Empty) returns (SampleData) {}
}

message SampleData {
  int32 id = 1;
  string name = 2;
  bool enjoys_coding = 3;
}

message Empty {}
Örnek - Unary
Şöyle yaparız
syntax = "proto3"
option java_multiple_files = true;
option java_package = "com.grpc.hello";
option java_outer_classname = "HelloProto";

service Hello {
  rpc SayHello (HelloRequest) returns (HelloReply)
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string name = 1;
}
Örnek - Tüm Kullanım Çeşitleri
Şöyle yaparız
syntax = "proto3";

package calculator;

option java_package = "com.vinsguru.calculator";
option java_multiple_files = true;

message Input {
  int32 number = 1;
}

message Output {
  int64 result = 1;
}

service CalculatorService {
  // unary
  rpc findFactorial(Input) returns (Output) {};
  // server stream
  rpc getAllFactors(Input) returns (stream Output) {};
  // client stream
  rpc sumAll(stream Input) returns (Output) {};
  // bi-directional stream
  rpc findPrime(stream Input) returns (stream Output) {};
}
Örnek - Unary + Bi-Directional Streaming
Şöyle yaparız. 
- generateRandomUser servisi unary'dir. 
- generateRandomUserStream servisi bi-directional'dır. Hem metod parametresinden hem de returns parametresinde stream kelimesi var.
syntax = "proto3";

package model;
import "google/protobuf/timestamp.proto";

option java_package = "com.userdetails.model";
option java_multiple_files = true;

message UserDetailsRequest {
  string firstName = 1;
  string lastName = 2;
  string city = 3;
}

message UserDetailsResponse {
  string id = 1;
  int32 numericId = 2;
  string firstName = 3;
  string lastName = 4;
  string city = 5;
}

service UserDetailsService {
  rpc generateRandomUser(UserDetailsRequest) returns (UserDetailsResponse) {};
  rpc generateRandomUserStream(stream UserDetailsRequest) returns
(stream UserDetailsResponse) {};
}

6 Ağustos 2020 Perşembe

gRPC - gRPC Remote Procedure Calls

Giriş
Microservis mimarisinde REST veya gRPC sıkça kullanılıyor. gRPC kullanabilmek için ProtoBuf bilmek gerekiyor. ProtoBuf yazısına bakabilirsiniz.

g Harfi Ne Anlama Gelir
Açıklaması şöyle. Liste burada
'g' stands for something different every gRPC release:
gRPC ve REST Karşılaştırması
gRPC'nin REST'e tercih edilmesi için bazı sebepler şöyle
Following are some reasons you should choose gRPC over Rest:
1) gRPC transfer binary data as payload rather then text which makes communication much faster and compact.
2) gRPC use HTTP/2 with long-lived connections so overhead of making connection per request can be avoided.
3) gRPC is type-safe so if you are expecting an integer then nobody can send it as a string.
4) gRPC is few millisecond faster then REST. So if millisecond matter for you then gRPC can be good choice.
5) gRPC supports streaming so if you are looking for distributed streaming support gRPC can be pretty useful in this case.
Bu sebepler, şu avantajları getiriyor.
gRPC is very good for the streaming requirements and if you want to avoid making connections per request. In the case of a microservice architecture it has the added advantage of a reduction of payload, saving the connection cost and type-safe contract.

gRPC client also supports reactive way of handling the request, so if you are developing the reactive architecture then gRPC can support that too.
gRPC Protobuf İle Çalışır
Açıklaması şöyle
gRPC uses protocol buffers by default.
gRPC ve Diğer Transportlar
Açıklaması şöyle
gRPC works with many transports, by default it uses HTTP/2 but it can also be implemented on QUIC , Cronet, etc.
gRPC ve HTTP/2 Transport
HTTP/2 ile çalışır. Açıklaması şöyle.
...gRPC requires more intentional design by providing an interface specification (protobuf) and requires HTTP/2 as its protocol, which currently doesn’t have wide browser support. However, gRPC offers significant advantages including a compact binary message format, bi-directional streaming and improved performance at scale.
Şeklen şöyle

Açıklaması şöyle. Burada binary gRPC paketinin nasıl HTTP/2 POST isteği ile gönderildiği anlatılıyor
In a typical gRPC call, the following steps take place.
1. It all starts with a client workflow initiating an RPC call.
2. Once RPC starts, the client stub encodes the message in binary format. And, then it creates an HTTP POST request with the encoded message.
3. Afterward, the encoded message is sent over the channel. A gRPC channel provides a connection to a gRPC server on a specified host and port.
4. On the server-side, the server hands over the encoded message to the auto-generated server stub.
5. After receiving the message, the server stub deserializes the message into a language-specific data structure.
6. And finally, the server stub makes a call to the overridden service method and passes the parsed message.

Maven Dependency
gRPC Maven Dependency yazısına taşıdım

Service Definitions in gRPC
4 çeşit servis tanımı var
1. Unary . Request, response ile aynıdır.
2. Server Streaming
3. Client Streaming
4. Bi-Directional Streaming

1. Unary 
Klasik request-response çağrısı. Senkron veya asenkron çalışabilir.

2. Client Streaming
Açıklaması şöyle
Client keeps on sending a request to the server by using a single TCP connection. The server might accept all the messages and sends a single response back. Use case: File upload functionality
3. Server Streaming
Açıklaması şöyle. Dashboard vs gibi için kullanılabilir.
Server sends multiple messages to the client via single TCP connection. Use case: Pagination or Server pushes periodic updates to the client asynchronously.
4. Bi-Directional Streaming
Açıklaması şöyle
Client and Server can keep on sharing messages via single TCP connection. Use case: Chat application or GPS or Client & server have to work together in an interactive way to complete a task
protobuf
gRPC protobuf yazısına taşıdım

gRPC Gradle Plugin
gRPC Gradle Plugin yazısına taşıdım

gRPC Maven Plugin
Kod üretmek içindir. Sanırım en çok protobuf-maven-plugin kullanılıyor

Örnek - protoc-jar-maven-plugin
Şöyle yaparız
<plugin>
  <groupId>com.github.os72</groupId>
  <artifactId>protoc-jar-maven-plugin</artifactId>
  <version>3.7.1</version>
  <executions>
    <execution>
     <phase>generate-sources</phase>
      <goals>
        <goal>run</goal>
       </goals>
      <configuration>
        <includeMavenTypes>direct</includeMavenTypes>
        <inputDirectories>
          <include>${project.basedir}/src/main/Protobuf</include>
        </inputDirectories>
        <outputTargets>
          <outputTarget>
            <type>java</type>
            <outputDirectory>
              ${project.basedir}/target/generated-sources/protobuf
            </outputDirectory>
        </outputTarget>
        <outputTarget>
          <type>grpc-java</type>
          <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.30.0</pluginArtifact>
          <outputDirectory>
            ${project.basedir}/target/generated-sources/protobuf
          </outputDirectory>
        </outputTarget>
      </outputTargets>
    </configuration>
  </execution>
  </executions>
</plugin
Örnek - protobuf-maven-plugin
protobuf plugin yazısına taşıdım

gRPC Server
gRPC Server yazısına taşıdım

gRPC Service
gRP Service yazısına taşıdım

gRPC Client
gRPC Client yazısına taşıdım