Java Grpc實(shí)例創(chuàng)建負(fù)載均衡詳解
Grpc是googe開發(fā)的,是一款語言中立、平臺中立、開源的遠(yuǎn)程過程調(diào)用(RPC)系統(tǒng)。新公司的項目服務(wù)之間的調(diào)用使用的Grpc來實(shí)現(xiàn)服務(wù)間的調(diào)用,這邊一開始接到的工作內(nèi)容是基于Nginx實(shí)現(xiàn)Grpc服務(wù)端的負(fù)載均衡。Nginx的1.13及以上版本是支持grpc的反向代理和負(fù)載均衡的。但是公司的nginx服務(wù)器的版本是1.10的,所以沒辦法直接使用grpc的代理。只能使用更底層的tcp層的負(fù)載均衡。最終服務(wù)跑起來是感覺挺簡單的,但是nginx的基礎(chǔ)太差,所以過程有點(diǎn)曲折。還是記錄下吧。
文章分兩部分,一個是創(chuàng)建簡單的Grpc客戶端和服務(wù)端的例子(其實(shí)也是用的網(wǎng)上的demo,這邊就貼一下源碼,講下更細(xì)的實(shí)現(xiàn)步驟),然后對比下Nginx的Grpc負(fù)載均衡和Tcp的負(fù)載均衡。
一、Java創(chuàng)建Grpc客戶端和服務(wù)端的例子(創(chuàng)建的配置信息相關(guān)的代碼基本網(wǎng)上博客的,忘記是哪篇文章了,所以暫時沒法給出轉(zhuǎn)載鏈接。)
1、在開發(fā)工具ide上創(chuàng)建一個maven project。打包方式選擇jar。
2、在POM.xml上增加grpc相關(guān)的依賴及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下面創(chuàng)建proto文件夾,并在里面創(chuàng)建一個hello.proto文件。具體如下截圖。
4、在hello.proto文件上輸入,相應(yīng)的配置信息,用來映射生成java代碼。里面的內(nèi)容就是生成一個MyRPC的服務(wù)提供一個sayHi的接口,接口需要傳遞一個request類的實(shí)例,該request實(shí)例只有一個name的字段。然后進(jìn)行相應(yīng)的業(yè)務(wù)代碼處理之后,返回一個response類的實(shí)例,也是只有一個name的字段。
如果進(jìn)行到這邊,看到第2步添加依賴上面的<execution>標(biāo)簽可能報錯,先暫時不要管他。直接進(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)行項目,右擊項目Run as -->maven build....->protobuf:compile以及protobuf:compile-custom,這樣就編譯生成了相應(yīng)的代碼了。不過存放的路徑不對,需要自己拷貝到相應(yīng)的項目目錄下。
6、grpc的客戶端和服務(wù)端代碼需要自己編寫。不過這一塊的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 { //這個部分啟動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(); } }
客戶端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、接下來就是才是比較關(guān)鍵的一步,實(shí)現(xiàn)自己的grpc服務(wù)端的業(yè)務(wù)代碼。主要的關(guān)鍵步驟就是繼承g(shù)rpc自動映射出來的抽象類。是不是很熟悉,沒錯就是proto文件里面配置的服務(wù)。然后重寫服務(wù)里面配置的方法即可。最后放心大膽的去根據(jù)傳遞的request參數(shù)去做相關(guān)的業(yè)務(wù)邏輯的處理。并用response封裝需要返回的接口。(此處的request與response均是grcp根據(jù)proto配置文件映射出來的相關(guān)實(shí)體類。)
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ù)端和客戶端的代碼改動都很小。只需調(diào)整ip和port的值即可。其他的不需要改動。
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; } } }
最后分別啟動nginx1.12.2和nginx1.17.0,并在ide上啟動服務(wù)端和客戶端,更改相應(yīng)的客戶端端口。就可以看到控制臺打印不同的信息了。tcp和grcp的負(fù)載均衡的效果是不一樣的。這也是我客戶端new 了一個client,然后又new 了一個client2的原因。比較懶,效果圖就不貼了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 使用Java實(shí)現(xiàn)6種常見負(fù)載均衡算法
- Java實(shí)現(xiàn)5種負(fù)載均衡算法(小結(jié))
- Java負(fù)載均衡算法實(shí)現(xiàn)之輪詢和加權(quán)輪詢
- java開發(fā)Dubbo負(fù)載均衡與集群容錯示例詳解
- 使用Java實(shí)現(xiàn)5種負(fù)載均衡算法實(shí)例
- 詳解Java實(shí)現(xiàn)負(fù)載均衡的幾種算法代碼
- Java?Ribbon與openfeign區(qū)別和用法講解
- Java中的服務(wù)發(fā)現(xiàn)與負(fù)載均衡及Eureka與Ribbon的應(yīng)用小結(jié)
相關(guān)文章
IDEA2022 提示更新 TKK失敗請檢查網(wǎng)絡(luò)連接的問題
這篇文章主要介紹了IDEA2022 提示:更新 TKK 失敗,請檢查網(wǎng)絡(luò)連接,本文給大家分享解決方案,對idea2022提示更新TKK失敗感興趣的朋友跟隨小編一起看看吧2022-11-11Java數(shù)據(jù)類型之引用數(shù)據(jù)類型解讀
這篇文章主要介紹了Java數(shù)據(jù)類型之引用數(shù)據(jù)類型,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07SpringBoot Admin升級boot等組件版本后無法監(jiān)控微服務(wù)問題
這篇文章主要介紹了SpringBoot Admin升級boot等組件版本后無法監(jiān)控微服務(wù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08如何優(yōu)雅的拋出Spring Boot注解的異常詳解
這篇文章主要給大家介紹了關(guān)于如何優(yōu)雅的拋出Spring Boot注解的異常的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-12-12SpringCloud注冊中心之consul詳細(xì)講解使用方法
Consul是一款由HashiCorp公司開源的,用于服務(wù)治理的軟件,Spring Cloud Consul對其進(jìn)行了封裝,這篇文章主要介紹了springcloud組件consul服務(wù)治理,需要的朋友可以參考下2022-11-11web.xml?SpringBoot打包可執(zhí)行Jar運(yùn)行SpringMVC加載流程
這篇文章主要為大家介紹了web.xml?SpringBoot打包可執(zhí)行Jar運(yùn)行SpringMVC加載流程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04