本文主要讨论通过grpc-java开发的普通的java grpc工程,以多实例的方式部署在容器编排平台kubernetes(以下简称k8s)上,如何能够实现让同样部署在k8s
集群内的客户端请求流量均衡的分发到多个grpc应用部署实例上去。
package com.example.grpcserver;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import java.io.IOException;
public class ProductInfoServer {
Server server;
public static void main(String[] args) {
ProductInfoServer productInfoServer = new ProductInfoServer();
productInfoServer.startServer();
productInfoServer.blockUntilShutdown();
}
private void startServer(){
int port = 50501;
try {
server = ServerBuilder.forPort(port).addService(new ProductInfoImpl()).build().start();
Runtime.getRuntime().addShutdownHook(new Thread( ()-> {
ProductInfoServer.this.stop();
}));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void stop(){
if(server != null){
server.shutdown();
}
}
private void blockUntilShutdown(){
if (server != null){
try {
System.out.println("begin =====server.awaitTermination();");
server.awaitTermination();
System.out.println("end =====server.awaitTermination();");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
部分源码:
package com.example.grpccli;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.javaboy.grpc.demo.Product;
import org.javaboy.grpc.demo.ProductId;
import org.javaboy.grpc.demo.ProductInfoGrpc;
public class ProductClient {
public static void main(String[] args) {
// 请注意此处是要连接的service暴露的端口
int port = 50501;
String serverAddr = "grpc-server-headless-srv.platform";
String dnsAddr = "dns:///"+serverAddr+":"+port;
System.out.println("dnsAddr: " + dnsAddr);
ManagedChannel managedChannel = ManagedChannelBuilder.forTarget("dns:///"+serverAddr+":"+port)
.defaultLoadBalancingPolicy("round_robin").usePlaintext().build();
ProductInfoGrpc.ProductInfoBlockingStub stub = ProductInfoGrpc.newBlockingStub(managedChannel);
// 循环分别创建和查询100次产品
for(int i=0; i<100; i++){
Product product = Product.newBuilder().setId("" + i).
setName("TH项目-" + i).
setPrice(i).
setDescription("grpc实战项目-" + i).
build();
// 添加产品
ProductId id = stub.addProduct(product);
System.out.println("我是增加产品: "+ id.getValue());
// 查询产品
Product prd = stub.getProduct(ProductId.newBuilder().setValue("" + i).build());
System.out.println("我是查询产品:" + prd.toString());
}
}
}
此处直接使用Kubesphere平台进行部署
注意客户端代码此处URI配置为(dns:///service:port)
服务端实例1和服务端实例2各接收到客户端50%的请求流量