RPC(Remote Procedure Call,远程过程调用)的核心思想是:让你像调用本地函数一样调用远程服务器上的函数。下面我用「概念 + 通用步骤 + 示例」的方式,帮你快速理解怎么用。
| 框架 | 语言 | 特点 |
|---|---|---|
| gRPC | 多语言 | 高性能,基于 HTTP/2 + Protobuf |
| Thrift | 多语言 | Facebook 出品 |
| Dubbo | Java | 国内常用 |
| JSON-RPC | 通用 | 简单,基于 JSON |
| XML-RPC | 通用 | 老牌,已较少用 |
.proto 文件)syntax = "proto3";
service HelloService {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
protoc --go_out=. --go-grpc_out=. hello.proto
type server struct{}
func (s *server) SayHello(ctx context.Context, req *HelloRequest) (*HelloReply, error) {
return &HelloReply{
Message: "Hello " + req.Name,
}, nil
}
func main() {
lis, _ := net.Listen("tcp", ":50051")
s := grpc.NewServer()
RegisterHelloServiceServer(s, &server{})
s.Serve(lis)
}
conn, _ := grpc.Dial("localhost:50051", grpc.WithInsecure())
client := NewHelloServiceClient(conn)
resp, _ := client.SayHello(context.Background(), &HelloRequest{Name: "Tom"})
fmt.Println(resp.Message)
✅ 客户端完全感觉不到这是远程调用
请求:
{
"jsonrpc": "2.0",
"method": "add",
"params": [1, 2],
"id": 1
}
响应:
{
"jsonrpc": "2.0",
"result": 3,
"id": 1
}
适合:前端 ↔ 后端、轻量服务
✅ 微服务之间通信
✅ 高性能内部调用
✅ 多语言系统协作
❌ 不适合浏览器直接调用(用 REST 更好)
如果你告诉我:
我可以直接给你可运行的最小示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。