1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- package main
- import (
- "../clientImpl"
- "crypto/tls"
- "git.wanpinghui.com/WPH/go_common/wph/logger"
- "google.golang.org/grpc"
- "google.golang.org/grpc/credentials"
- "google.golang.org/grpc/grpclog"
- "log"
- "os"
- "time"
- )
- // 简单请求客户端,用于测试k8s环境本身的请求分发能力
- func main() {
- //以k8s service名来建立连接
- //serviceConn, err := grpc.Dial("grpc-example:80", grpc.WithInsecure())
- //if err != nil {
- // log.Fatalf("did not connect: %v", err)
- //}
- //defer func() {
- // _ = serviceConn.Close()
- //}()
- //
- //log.Println("==== Calling grpc-example by k8s service ====")
- //clientImpl.MakeCalls(serviceConn, 10)
- // 以k8s ingress来建立连接
- // 用qcloud ingress访问,不论是在service中网络type设为负载均衡所添加的,或手工添加指向NodePort的4层负载均衡,对grpc均不能真正起到负载均衡的效果
- // qcloud类型7层http/https ingress,直接无法访问通grpc服务
- //ingressConn, err := grpc.Dial("10.7.255.37:80", grpc.WithInsecure())
- // 用nginx ingress访问,通过配置DNS服务器做域名解析(推荐指向nginx controller内网service ip),在客户端的yaml文件中配置本地hosts的方式无效
- // 详细访问路径:解析域名 -> nginx controller的service的ip -> nginx controller pod(TKE中额外手工部署ingress-nginx后添加的)->
- // 转发到具体nginx ingres的yaml配置文件中指向的后端service(创建或更新nginx ingress时,其中的backend配置都会自动同步到nginx controller pod里的nginx.conf中,可进入该pod查看)
- // 读文件证书
- //certFile := `./ex_tls.crt` // 服务器上的证书路径,可以在构件docker镜像时复制,但k8s环境更建议从Secret中挂载
- //isExisted, _ := pathExists(certFile)
- //if !isExisted {
- // certFile = `/Users/marion/Documents/project/test/gotest/grpc-demo/tls/ex_tls.crt` // 本地测试时的证书文件绝对路径
- //}
- //crt, _ := credentials.NewClientTLSFromFile(certFile, "example.wanpinghui.com")
- // 跳过证书验证,但直接grpc.WithInsecure()不通
- var tlsConf tls.Config
- tlsConf.InsecureSkipVerify = true
- crt := credentials.NewTLS(&tlsConf)
- ingressConn, err := grpc.Dial("example.wanpinghui.com:443", grpc.WithTransportCredentials(crt)) // 推荐把域名解析到nginx controller service内网ip
- //ingressConn, err := grpc.Dial("example.wanpinghui.com:443", grpc.WithInsecure())
- if err != nil {
- log.Fatalf("did not connect: %v", err)
- }
- defer func() {
- _ = ingressConn.Close()
- }()
- // 打印更详细的日志
- l := logger.New()
- grpclog.SetLoggerV2(l)
- log.Println("==== Calling grpc-example by k8s ingress ====")
- clientImpl.MakeCalls(ingressConn, 10)
- // 停顿10秒再请求,此时可手工增减pod,以测试pod掉线或新节点上线的情况
- println(`sleeping ------------------------------------------------------->`)
- time.Sleep(10 * time.Second)
- clientImpl.MakeCalls(ingressConn, 10)
- }
- func pathExists(path string) (bool, error) {
- _, err := os.Stat(path)
- if err == nil {
- return true, nil
- }
- if os.IsNotExist(err) {
- return false, nil
- }
- return false, err
- }
|