首页 文章资讯内容详情

golang中的rpc包用法

2026-06-01 4 花语

本文内容纲要:

-介绍 -示例

RPC,即RemoteProcedureCall(远程过程调用),说得通俗一点就是:调用远程计算机上的服务,就像调用本地服务一样。

我所在公司的项目是采用基于Restful的微服务架构,随着微服务之间的沟通越来越频繁,就希望可以做成用rpc来做内部的通讯,对外依然用Restful。于是就想到了golang标准库的rpc包和google的grpc。

这篇文章重点了解一下golang的rpc包。

介绍

golang的rpc支持三个级别的RPC:TCP、HTTP、JSONRPC。但Go的RPC包是独一无二的RPC,它和传统的RPC系统不同,它只支持Go开发的服务器与客户端之间的交互,因为在内部,它们采用了Gob来编码。

GoRPC的函数只有符合下面的条件才能被远程访问,不然会被忽略,详细的要求如下:

函数必须是导出的(首字母大写) 必须有两个导出类型的参数, 第一个参数是接收的参数,第二个参数是返回给客-户端的参数,第二个参数必须是指针类型的 函数还要有一个返回值error

举个例子,正确的RPC函数格式如下:

func(t*T)MethodName(argTypeT1,replyType*T2)error

T、T1和T2类型必须能被encoding/gob包编解码。

示例

举一个http的例子。

下面是http服务器端的代码:

packagemain import( "errors" "net" "net/rpc" "log" "net/http" ) typeArgsstruct{ A,Bint } typeQuotientstruct{ Quo,Remint } typeArithint func(t*Arith)Multiply(args*Args,reply*int)error{ *reply=args.A*args.B returnnil } func(t*Arith)Divide(args*Args,quo*Quotient)error{ ifargs.B==0{ returnerrors.New("dividebyzero") } quo.Quo=args.A/args.B quo.Rem=args.A%args.B returnnil } funcmain(){ arith:=new(Arith) rpc.Register(arith) rpc.HandleHTTP() l,e:=net.Listen("tcp",":1234") ife!=nil{ log.Fatal("listenerror:",e) } http.Serve(l,nil) }

简单分析一下上面的例子,先实例化了一个Arith对象arith,然后给arith注册了rpc服务,然后把rpc挂载到http服务上面,当http服务打开的时候我们就可以通过rpc客户端来调用arith中符合rpc标准的的方法了。

请看客户端的代码:

packagemain import( "net/rpc" "log" "fmt" ) typeArgsstruct{ A,Bint } typeQuotientstruct{ Quo,Remint } funcmain(){ client,err:=rpc.DialHTTP("tcp","127.0.0.1:1234") iferr!=nil{ log.Fatal("dialing:",err) } //Synchronouscall args:=&Args{7,8} varreplyint err=client.Call("Arith.Multiply",args,&reply) iferr!=nil{ log.Fatal("aritherror:",err) } fmt.Printf("Arith:%d*%d=%d\n",args.A,args.B,reply) //Asynchronouscall quotient:=new(Quotient) divCall:=client.Go("Arith.Divide",args,quotient,nil) replyCall:=<-divCall.Done //willbeequaltodivCall ifreplyCall.Error!=nil{ log.Fatal("aritherror:",replyCall.Error) } fmt.Printf("Arith:%d/%d=%d...%d",args.A,args.B,quotient.Quo,quotient.Rem) //checkerrors,print,etc. }

简单说明下,先用rpc的DialHTTP方法连接服务器端,调用服务器端的函数就要使用Call方法了,Call方法的参数和返回值已经很清晰的表述出rpc整体的调用逻辑了。

我们把服务器端跑起来,再把客户端跑起来,这时候客户端会输出:

Arith:7*8=56 Arith:7/8=0...7

到此,整个rpc的调用逻辑就完成了。

本文内容总结:介绍,示例,

原文链接:https://www.cnblogs.com/andyidea/p/6525714.html