Java Grpc 인 스 턴 스 생 성 부하 균형 상세 설명

Grpc 는 googe 가 개발 한 것 으로 언어 중립,플랫폼 중립,오픈 소스 의 원 격 프로 세 스 호출(RPC)시스템 이다.새 회사 의 프로젝트 서비스 간 호출 에 사용 되 는 Grpc 는 서비스 간 호출 을 실현 합 니 다.여기 서 처음에 받 은 업무 내용 은 Nginx 를 바탕 으로 Grpc 서버 의 부하 균형 을 실현 하 는 것 입 니 다.Nginx 의 1.13 이상 버 전 은 grpc 의 역방향 에이전트 와 부하 균형 을 지원 합 니 다.그러나 회사 의 nginx 서버 버 전 은 1.10 이 므 로 grpc 프 록 시 를 직접 사용 할 수 없습니다.더 밑바닥 tcp 층 의 부하 균형 만 사용 할 수 있 습 니 다.최종 서 비 스 는 뛰 기 에는 매우 간단 하지만 nginx 의 기초 가 너무 나 빠 서 과정 이 약간 우여곡절 하 다.기록 하 세 요.
글 은 두 부분 으로 나 뉘 는데 하 나 는 간단 한 Grpc 클 라 이언 트 와 서버 를 만 드 는 예 이다.
1.자바 가 Grpc 클 라 이언 트 와 서버 를 만 드 는 예(설정 정보 와 관련 된 코드 기본 인터넷 블 로 그 를 만 든 것 은 어떤 글 인지 잊 어 버 려 서 링크 를 옮 길 수 없습니다.)
1.개발 도구 id 에 maven procject 를 만 듭 니 다.포장 방식 선택 jar.
2.POM.xml 에 grpc 관련 의존 및 maven 패키지 플러그 인 추가

<dependencies>
  <dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-netty</artifactId>
    <version>1.17.1</version>
  </dependency>
  <dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-protobuf</artifactId>
    <version>1.17.1</version>
  </dependency>
  <dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-stub</artifactId>
    <version>1.17.1</version>
  </dependency>
</dependencies>
<build>
  <extensions>
    <extension>
      <groupId>kr.motd.maven</groupId>
      <artifactId>os-maven-plugin</artifactId>
      <version>1.4.1.Final</version>
    </extension>
  </extensions>
  <plugins>
    <plugin>
      <groupId>org.xolstice.maven.plugins</groupId>
      <artifactId>protobuf-maven-plugin</artifactId>
      <version>0.5.0</version>
      <configuration>
        <protocArtifact>com.google.protobuf:protoc:3.0.0:exe:${os.detected.classifier}</protocArtifact>
        <pluginId>grpc-java</pluginId>
        <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.0.0:exe:${os.detected.classifier}</pluginArtifact>
      </configuration>
      <executions>
        <execution>
          <goals>
            <goal>compile</goal>
            <goal>compile-custom</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
  </plugins>
</build>
3.프로젝트 아래 경로 src/main 아래 에 proto 폴 더 를 만 들 고 그 안에 hello.proto 파일 을 만 듭 니 다.구체 적 으로 는 다음 과 같다.
  
4.hello.proto 파일 에 해당 하 는 설정 정 보 를 입력 하여 자바 코드 를 생 성 합 니 다.이 내용 은 MyRPC 서 비 스 를 만 들 고 sayHi 인 터 페 이 스 를 제공 하 는 것 입 니 다.인 터 페 이 스 는 request 류 의 인 스 턴 스 를 전달 해 야 합 니 다.이 request 인 스 턴 스 는 name 필드 만 있 습 니 다.그 다음 에 해당 하 는 업무 코드 처 리 를 한 후에 response 류 의 인 스 턴 스 를 되 돌려 주 는 것 도 name 필드 만 있 습 니 다.
이쪽 으로 진행 되면 두 번 째 단계 에 위 에 의존 하 는탭 을 추가 하 는 것 이 잘못 되 었 을 수 있 으 니 당분간 신경 쓰 지 마 세 요.직접 5 단계 진행.

syntax = "proto3";
option java_package = "com.qidai.proto";
option java_outer_classname = "MyThing";

message Request {
  string name = 1;
}
message Response {
  string name = 2;
}
service MyRPC {
  rpc sayHi(Request) returns(Response);
}
5.프로젝트 실행,오른쪽 클릭 항목 Run as-->maven build...->protobuf:copile 및 protobuf:copile-custom,이렇게 컴 파일 하여 해당 하 는 코드 를 생 성 합 니 다.그러나 저 장 된 경로 가 잘못 되 었 으 므 로 해당 항목 디 렉 터 리 에 복사 해 야 합 니 다.

6.grpc 의 클 라 이언 트 와 서버 코드 는 스스로 작성 해 야 합 니 다.근 데 이 데 모 는 다 됐어 요.c+v 그리고 자신 이 필요 로 하 는 것 으로 바 꾸 면 됩 니 다.
서버 데모:

package server;
import com.qidai.proto.MyRPCGrpc;
import com.qidai.proto.MyThing;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import service.RequestImpl;

import java.io.IOException;
public class Server {
  private static final int PORT = 2222;
  private final io.grpc.Server server;
  public Server() throws IOException {
    //      server
    this.server = ServerBuilder.forPort(PORT)
        .addService(new RequestImpl())
        .build()
        .start();
    System.out.println("Server1 Started ...");
  }
  private void stop() {
    if (server != null) {
      server.shutdown();
    }
  }
  private void blockUntilShutdown() throws InterruptedException {
    if (server != null) {
      server.awaitTermination();
    }
  }
  public static void main(String[] args) throws IOException, InterruptedException {
    Server server = new Server();
    //block Server    
    server.blockUntilShutdown();
  }
  
}
클 라 이언 트 데모

package client;
import com.qidai.proto.MyRPCGrpc;
import com.qidai.proto.MyRPCGrpc.MyRPCBlockingStub;
import com.qidai.proto.MyThing;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import java.util.concurrent.TimeUnit;
public class Client {
  private final ManagedChannelBuilder<?> managedChannelBuilder;
  private final MyRPCBlockingStub blockingStub;
  private final ManagedChannel channel;
  public Client(String name, int port) {
    managedChannelBuilder = ManagedChannelBuilder.forAddress(name, port);
    channel = managedChannelBuilder.usePlaintext().build();
    blockingStub = MyRPCGrpc.newBlockingStub(channel);
  }
  public void shutdown() throws InterruptedException {
    channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
  }
  public void sayHi(String name){
    MyThing.Request request = MyThing.Request.newBuilder().setName(name).build();
    MyThing.Response response = blockingStub.sayHi(request);
    System.out.println(response.getName());
  }
  public static void main(String[] args) throws Exception{
    Client client = new Client("localhost", 5005);
    for (int i = 0; i < 10; i++) {
      Thread.sleep(1000);
      //  rpc       
      client.sayHi("Hello Server1111 ->5005 " + i);
    }
    client.shutdown();
    Client client2 = new Client("localhost", 5005);
    for (int i = 0; i < 10; i++) {
      Thread.sleep(1000);
      //  rpc       
      client2.sayHi("Hello Server2222 ->5005 " + i);
    }
    client2.shutdown();
  }
}
7.다음은 비교적 관건 적 인 단계 로 자신의 grpc 서버 의 업무 코드 를 실현 하 는 것 이다.주요 한 관건 적 인 절 차 는 grpc 가 자동 으로 매 핑 된 추상 류 를 계승 하 는 것 이다.익숙 하지 않 습 니까?맞습니다.proto 파일 에 설 치 된 서비스 입 니 다.그리고 서비스 에 설 치 된 방법 을 다시 쓰 면 됩 니 다.마지막 으로 안심 하고 대담 하 게 전달 하 는 request 파라미터 에 따라 관련 업무 논리 적 처 리 를 한다.되 돌아 올 인 터 페 이 스 를 response 로 밀봉 합 니 다.(이 곳 의 request 와 response 는 모두 grcp 가 proto 설정 파일 에 따라 매 핑 된 관련 실체 클래스 입 니 다.)

package service;


import com.qidai.proto.MyRPCGrpc.MyRPCImplBase;
import com.qidai.proto.MyThing.Response;

public class RequestImpl extends MyRPCImplBase {
  
  @Override
  public void sayHi(com.qidai.proto.MyThing.Request request,
      io.grpc.stub.StreamObserver<com.qidai.proto.MyThing.Response> responseObserver) {
    //proto      response    
    Response response;
    
    System.out.println("Request>>>say::" + request.getName());
    //AccountQryResponse response = QryAccountProto.AccountQryResponse.newBuilder().setRc(1).setAmount(666).build();
    response = Response.newBuilder().setName("Response11111>>>say:::hello_client"+request.getName()).build();
    responseObserver.onNext(response);
    responseObserver.onCompleted();
    
    }
  
}
2.Grpc 서 비 스 는 nginx(1.12.2)를 바탕 으로 부하 균형 을 실현 한다.다음은 nginx 와 관련 된 설정 을 직접 붙 이 고 서버 와 클 라 이언 트 의 코드 변경 이 적 습 니 다.ip 와 port 의 값 만 조정 하면 됩 니 다.다른 건 바 꿀 필요 없어.
TCP 계층 부하 균형 설정

stream {

  log_format proxy '$remote_addr [$time_local] '
         '$protocol $status $bytes_sent $bytes_received '
         '$session_time "$upstream_addr" '
         '"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';
  include ./conf.d/*.tcpstream;

  upstream grpc {
    server 127.0.0.1:2223;
    server 127.0.0.1:2222;
  }

  server {
  
  error_log    logs/device5001_error.log;
  access_log   logs/device5001_access.log proxy;

    listen 5005;
    proxy_pass grpc;
  }
  
}
grpc 의 부하 균형 설정(grpc 의 지원 은 nginx 1.13 이후 에 만 있 기 때문에 여 기 는 1.17.0)

http {
  include    mime.types;
  default_type application/octet-stream;

  log_format main '$remote_addr - $remote_user [$time_local] "$request" '
           '$status $body_bytes_sent "$http_referer" '
           '"$http_user_agent" "$http_x_forwarded_for"';

  access_log logs/access.log main;

  sendfile    on;
 
  keepalive_timeout 65;

  gzip on;

  upstream grpcservers {
  server 127.0.0.1:2222;
  server 127.0.0.1:2223;
  }

  server {
    listen    8080 http2;
    server_name localhost;
       
    location / {
      grpc_pass grpc://grpcservers;
    }
  }
}
마지막 으로 nginx 1.12.2 와 nginx 1.17.0 을 시작 하고 ide 에서 서버 와 클 라 이언 트 를 시작 하여 해당 하 는 클 라 이언 트 포트 를 변경 합 니 다.콘 솔 에서 다른 정 보 를 인쇄 하 는 것 을 볼 수 있 습 니 다.tcp 와 grcp 의 부하 균형 효 과 는 다르다.이것 도 제 클 라 이언 트 new 가 client 를 만 들 었 고 new 가 client 2 를 만 든 이유 입 니 다.게 으 르 면 효과 도 는 붙 이지 않 는 다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기