欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java Grpc實(shí)例創(chuàng)建負(fù)載均衡詳解

 更新時(shí)間:2020年03月20日 10:35:32   作者:風(fēng)繾云流  
這篇文章主要介紹了Java Grpc實(shí)例創(chuàng)建負(fù)載均衡詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

Grpc是googe開(kāi)發(fā)的,是一款語(yǔ)言中立、平臺(tái)中立、開(kāi)源的遠(yuǎn)程過(guò)程調(diào)用(RPC)系統(tǒng)。新公司的項(xiàng)目服務(wù)之間的調(diào)用使用的Grpc來(lái)實(shí)現(xiàn)服務(wù)間的調(diào)用,這邊一開(kāi)始接到的工作內(nèi)容是基于Nginx實(shí)現(xiàn)Grpc服務(wù)端的負(fù)載均衡。Nginx的1.13及以上版本是支持grpc的反向代理和負(fù)載均衡的。但是公司的nginx服務(wù)器的版本是1.10的,所以沒(méi)辦法直接使用grpc的代理。只能使用更底層的tcp層的負(fù)載均衡。最終服務(wù)跑起來(lái)是感覺(jué)挺簡(jiǎn)單的,但是nginx的基礎(chǔ)太差,所以過(guò)程有點(diǎn)曲折。還是記錄下吧。

文章分兩部分,一個(gè)是創(chuàng)建簡(jiǎn)單的Grpc客戶(hù)端和服務(wù)端的例子(其實(shí)也是用的網(wǎng)上的demo,這邊就貼一下源碼,講下更細(xì)的實(shí)現(xiàn)步驟),然后對(duì)比下Nginx的Grpc負(fù)載均衡和Tcp的負(fù)載均衡。

一、Java創(chuàng)建Grpc客戶(hù)端和服務(wù)端的例子(創(chuàng)建的配置信息相關(guān)的代碼基本網(wǎng)上博客的,忘記是哪篇文章了,所以暫時(shí)沒(méi)法給出轉(zhuǎn)載鏈接。)

  1、在開(kāi)發(fā)工具ide上創(chuàng)建一個(gè)maven project。打包方式選擇jar。

  2、在POM.xml上增加grpc相關(guān)的依賴(lài)及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、在項(xiàng)目下的路徑src/main下面創(chuàng)建proto文件夾,并在里面創(chuàng)建一個(gè)hello.proto文件。具體如下截圖。

  

  4、在hello.proto文件上輸入,相應(yīng)的配置信息,用來(lái)映射生成java代碼。里面的內(nèi)容就是生成一個(gè)MyRPC的服務(wù)提供一個(gè)sayHi的接口,接口需要傳遞一個(gè)request類(lèi)的實(shí)例,該request實(shí)例只有一個(gè)name的字段。然后進(jìn)行相應(yīng)的業(yè)務(wù)代碼處理之后,返回一個(gè)response類(lèi)的實(shí)例,也是只有一個(gè)name的字段。

    如果進(jìn)行到這邊,看到第2步添加依賴(lài)上面的<execution>標(biāo)簽可能報(bào)錯(cuò),先暫時(shí)不要管他。直接進(jìn)行第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、運(yùn)行項(xiàng)目,右擊項(xiàng)目Run as -->maven build....->protobuf:compile以及protobuf:compile-custom,這樣就編譯生成了相應(yīng)的代碼了。不過(guò)存放的路徑不對(duì),需要自己拷貝到相應(yīng)的項(xiàng)目目錄下。

  6、grpc的客戶(hù)端和服務(wù)端代碼需要自己編寫(xiě)。不過(guò)這一塊的demo已經(jīng)很全了。c+v然后改成自己的自己需要的就行了。

  服務(wù)端demo:

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 {
    //這個(gè)部分啟動(dòng)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防止關(guān)閉
    server.blockUntilShutdown();
  }
  
}

  客戶(hù)端demo

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);
      //進(jìn)行rpc調(diào)用的真正邏輯
      client.sayHi("Hello Server1111 ->5005 " + i);
    }
    client.shutdown();
    Client client2 = new Client("localhost", 5005);
    for (int i = 0; i < 10; i++) {
      Thread.sleep(1000);
      //進(jìn)行rpc調(diào)用的真正邏輯
      client2.sayHi("Hello Server2222 ->5005 " + i);
    }
    client2.shutdown();
  }
}

  7、接下來(lái)就是才是比較關(guān)鍵的一步,實(shí)現(xiàn)自己的grpc服務(wù)端的業(yè)務(wù)代碼。主要的關(guān)鍵步驟就是繼承g(shù)rpc自動(dòng)映射出來(lái)的抽象類(lèi)。是不是很熟悉,沒(méi)錯(cuò)就是proto文件里面配置的服務(wù)。然后重寫(xiě)服務(wù)里面配置的方法即可。最后放心大膽的去根據(jù)傳遞的request參數(shù)去做相關(guān)的業(yè)務(wù)邏輯的處理。并用response封裝需要返回的接口。(此處的request與response均是grcp根據(jù)proto配置文件映射出來(lái)的相關(guān)實(shí)體類(lèi)。)

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();
    
    }
  
}

  二、Grpc服務(wù)基于nginx(1.12.2)實(shí)現(xiàn)負(fù)載均衡。下面直接貼nginx相關(guān)的配置,服務(wù)端和客戶(hù)端的代碼改動(dòng)都很小。只需調(diào)整ip和port的值即可。其他的不需要改動(dòng)。

  TCP層負(fù)載均衡配置

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的負(fù)載均衡配置(grpc的支持在nginx1.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;
    }
  }
}

  最后分別啟動(dòng)nginx1.12.2和nginx1.17.0,并在ide上啟動(dòng)服務(wù)端和客戶(hù)端,更改相應(yīng)的客戶(hù)端端口。就可以看到控制臺(tái)打印不同的信息了。tcp和grcp的負(fù)載均衡的效果是不一樣的。這也是我客戶(hù)端new 了一個(gè)client,然后又new 了一個(gè)client2的原因。比較懶,效果圖就不貼了。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • java導(dǎo)出excel 瀏覽器直接下載或者或以文件形式導(dǎo)出

    java導(dǎo)出excel 瀏覽器直接下載或者或以文件形式導(dǎo)出

    這篇文章主要介紹了java導(dǎo)出excel 瀏覽器直接下載或者或以文件形式導(dǎo)出方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • IDEA在一個(gè)工作空間中管理多個(gè)項(xiàng)目的詳細(xì)步驟

    IDEA在一個(gè)工作空間中管理多個(gè)項(xiàng)目的詳細(xì)步驟

    這篇文章主要介紹了IDEA在一個(gè)工作空間中管理多個(gè)項(xiàng)目的詳細(xì)步驟,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-01-01
  • Java基礎(chǔ)之并發(fā)相關(guān)知識(shí)總結(jié)

    Java基礎(chǔ)之并發(fā)相關(guān)知識(shí)總結(jié)

    隨著摩爾定律逐步失效,cpu單核性能達(dá)到瓶頸,并發(fā)逐漸逐漸得到廣泛應(yīng)用,因而學(xué)習(xí)了解以及使用并發(fā)就顯得十分重要,但并發(fā)相關(guān)的知識(shí)比較瑣碎,不易系統(tǒng)學(xué)習(xí),因而本篇文章參照王寶令老師《Java并發(fā)編程》來(lái)勾勒出一張“并發(fā)全景圖”,需要的朋友可以參考下
    2021-05-05
  • 不了解這12個(gè)語(yǔ)法糖,別說(shuō)你會(huì)Java

    不了解這12個(gè)語(yǔ)法糖,別說(shuō)你會(huì)Java

    這篇文章主要介紹了不了解這12個(gè)語(yǔ)法糖,別說(shuō)你會(huì)Java,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • 詳解JAVA高質(zhì)量代碼之?dāng)?shù)組與集合

    詳解JAVA高質(zhì)量代碼之?dāng)?shù)組與集合

      在學(xué)習(xí)編程的過(guò)程中,我覺(jué)得不止要獲得課本的知識(shí),更多的是通過(guò)學(xué)習(xí)技術(shù)知識(shí)提高解決問(wèn)題的能力,這樣我們才能走在最前方,本文主要講述Java高質(zhì)量代碼之?dāng)?shù)組與集合
    2013-08-08
  • Hibernate中的多表查詢(xún)及抓取策略

    Hibernate中的多表查詢(xún)及抓取策略

    本文主要介紹了Hibernate中的多表查詢(xún)及抓取策略,具有很好的參考價(jià)值,下面跟著小編一起來(lái)看下吧
    2017-02-02
  • mybatis-plus與mybatis共存的實(shí)現(xiàn)

    mybatis-plus與mybatis共存的實(shí)現(xiàn)

    本文主要介紹了mybatis-plus與mybatis共存的實(shí)現(xiàn),文中根據(jù)實(shí)例編碼詳細(xì)介紹的十分詳盡,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • java字符串?dāng)?shù)字補(bǔ)齊位數(shù)詳解

    java字符串?dāng)?shù)字補(bǔ)齊位數(shù)詳解

    這篇文章主要介紹了java字符串?dāng)?shù)字補(bǔ)齊位數(shù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2025-03-03
  • springboot如何靜態(tài)加載@configurationProperties

    springboot如何靜態(tài)加載@configurationProperties

    這篇文章主要介紹了springboot如何靜態(tài)加載@configurationProperties,本文一個(gè)錯(cuò)誤案例和成功案例結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-07-07
  • springboot使用redis實(shí)現(xiàn)從配置到實(shí)戰(zhàn)

    springboot使用redis實(shí)現(xiàn)從配置到實(shí)戰(zhàn)

    本文主要介紹了springboot使用redis ,采用的是RedisTemplate的形式,還有一種采用spring支持的注解進(jìn)行訪(fǎng)問(wèn)緩存,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-08-08

最新評(píng)論