7 Aralık 2022 Çarşamba

gRPC Server API ServerBuilder Sınıfı

Giriş
Şu satırı dahil ederiz
import io.grpc.Server;
import io.grpc.ServerBuilder;
addService metodu
Örnek
Şöyle yaparız
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;

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

import com.google.protobuf.ByteString;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.InterruptedException;

public class TutorialServer {
  private Server server;

  static class FetchImpl extends FetchGrpc.FetchImplBase {...}

  public void listenAndServe() throws IOException, InterruptedException {
    this.start();
    this.server.awaitTermination();
  }

  private void start() throws IOException {
    this.server = ServerBuilder.forPort(this.serverPort)
                  .addService(new FetchImpl())
                  .build()
                  .start();

    Server theServer = this.server;
    Runtime.getRuntime()
      .addShutdownHook(
        new Thread() {
          public void run() {theServer.shutdown();}
        });
  }
main metodu için şöyle yaparız
public static void main(String ...args) {
  TutorialServer tsrv = new TutorialServer(9_876);

  try {
    tsrv.listenAndServe();
  } catch (Exception e) {
    ...
  }
}
executor metodu
Örnek
Şöyle yaparız
public void start() throws IOException {
  server = ServerBuilder.forPort(5_001)
    .addService(new GrpcApi())
    .executor(Executors.newFixedThreadPool(350, 
      new ThreadFactoryBuilder().setNameFormat("grpc-%d").build()))
    .build()
    .start();
}
shutdown metodu
Örnek
Şöyle yaparız
public class GrpcServer {

  private final int port;
  private final Server server;

  public GrpcServer(int port) {
    this.port = port;
    this.server = ServerBuilder.forPort(port).addService(new ProductService()).build();
  }

  public void start() throws IOException {
    server.start();
    log.info("Server Started on port {} ", port);
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread(
                () -> {
                  try {
                    this.stop();
                  } catch (InterruptedException e) {
                    e.printStackTrace();
                  }
                }));
  }

  private void stop() throws InterruptedException {
    if (server != null) {
      server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
    }
  }

  private void blockUntilShutDown() throws InterruptedException {
    if (this.server != null) {
      server.awaitTermination();
    }
  }
}
main metodu için şöyle yaparız
  public static void main(String[] args) throws IOException, InterruptedException {
    var productServer = new GrpcServer(3_000);
    productServer.start();
    productServer.blockUntilShutDown();
  }
}









Hiç yorum yok:

Yorum Gönder