Python等语言gRPC客户端能否通过IP或DNS连接远程服务端及获取代码示例
gRPC客户端通过IP/DNS域名连接远程服务端说明
结论
完全可以。gRPC基于HTTP/2实现传输,和常规网络请求的寻址逻辑一致,只要远程服务端的IP/DNS地址网络可达、对应监听端口开放、无防火墙/安全组拦截,任何语言开发的gRPC客户端都可以直接通过IP或DNS域名连接远程服务端,无需特殊改造。
代码示例
前置准备
已通过.proto服务定义文件生成对应语言的gRPC存根代码,提前安装对应语言的gRPC依赖包。
Python 示例
依赖安装
执行命令:pip install grpcio grpcio-tools
普通非加密连接代码
import grpc # 导入提前生成的proto存根代码 import helloworld_pb2 import helloworld_pb2_grpc def run(): # 此处直接替换为远程服务的实际地址即可 # IP连接示例:channel = grpc.insecure_channel('120.xx.xx.xx:50051') # 域名连接示例:channel = grpc.insecure_channel('grpc.yourdomain.com:50051') with grpc.insecure_channel('localhost:50051') as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello(helloworld_pb2.HelloRequest(name='test_user')) print("服务端返回结果:" + response.message) if __name__ == '__main__': run()
TLS加密连接代码(域名场景常用)
如果服务端配置了SSL证书,使用安全连接的示例如下:
import grpc import helloworld_pb2 import helloworld_pb2_grpc def run(): # 加载服务端可信证书 with open('server_root.crt', 'rb') as f: root_certs = f.read() credentials = grpc.ssl_channel_credentials(root_certificates=root_certs) # 使用域名+加密连接 channel = grpc.secure_channel('grpc.yourdomain.com:50051', credentials) stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello(helloworld_pb2.HelloRequest(name='test_user')) print("服务端返回结果:" + response.message) if __name__ == '__main__': run()
Go 示例
package main import ( "context" "log" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" pb "your_project_path/proto/helloworld" ) func main() { // 替换为远程服务的IP/域名+端口 targetAddr := "grpc.yourdomain.com:50051" // 建立连接 conn, err := grpc.Dial(targetAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { log.Fatalf("连接服务端失败: %v", err) } defer conn.Close() client := pb.NewGreeterClient(conn) // 发送请求 resp, err := client.SayHello(context.Background(), &pb.HelloRequest{Name: "test_user"}) if err != nil { log.Fatalf("请求失败: %v", err) } log.Printf("服务端返回结果:%s", resp.GetMessage()) }
注意事项
- 确保远程服务端的gRPC监听端口(默认常用50051)已放通安全组、防火墙规则,客户端和服务端网络链路连通
- 若使用域名连接,需确认客户端所在环境可正常解析该域名到正确的服务端IP
- 若服务端开启了TLS加密,禁止使用不安全连接配置,需加载对应SSL凭证建立安全连接
- gRPC原生支持DNS服务发现,部署在K8s等容器集群环境时,可直接使用集群内服务的DNS域名进行连接
内容的提问来源于stack exchange,提问作者Osama Natouf
相关产品推荐
相关产品推荐

