go語言RPC

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

RPC remote procedure call,遠端程序呼叫。

go語言對RPC的支援有以下要求:

1.以對象形式註冊RPC

2.RPC函數必須是對象的公用函數。public,也就是首字母大寫的函數

3.RPC函數必須有2個參數,類型為公用類型,或go內嵌類型。

4.RPC函數第2個參數作為傳回值,必須是指標類型。

5.RPC函數必須返回一個error類型的值。


func (this *T) MethodName(args T1,reply *T2) error 


預設以gob經行資料編碼與解碼。


TCP串連

/** * Created by Administrator on 13-12-31. */package mainimport ("errors""net/rpc""net""fmt""os")type Args struct {I , J int}type MyMethod intfunc (this *MyMethod) Mult(args *Args, reply *int) error {if args == nil || reply == nil {return errors.New("nil paramters !")}*reply = args.I*args.Jreturn nil}type DivResult struct {Quo, Rem int}func (this *MyMethod) Div(args *Args, reply *DivResult) error{if args == nil || reply == nil {return errors.New("nil paramters !")}if args.J == 0 {return errors.New("/0 !")}reply.Quo = args.I / args.Jreply.Rem = args.I % args.Jreturn nil}func main() {mm := new(MyMethod)server := rpc.NewServer()server.Register(mm)listener, err := net.Listen("tcp",":7777")        defer listener.Close()if err != nil {fmt.Fprintf(os.Stderr, "error %s\n", err.Error())return}server.Accept(listener)}

/** * Created by Administrator on 13-12-31. */package mainimport ("net/rpc""fmt""os")type Args struct {I , J int}type MyMethod int//func (this *MyMethod) Mult(args *Args, reply *int) error {//if args == nil || reply == nil {//return errors.New("nil paramters !")//}//*reply = args.I*args.J//return nil//}type DivResult struct {Quo, Rem int}//func (this *MyMethod) Div(args *Args, reply *DivResult) {//reply.Quo = args.I / args.J//reply.Rem = args.J % args.J//}func main() {pClient, err := rpc.Dial("tcp", "127.0.0.1:7777")if err != nil {fmt.Fprintf(os.Stderr, "err : %s\n", err.Error())return}defer pClient.Close()// 同步RPCvar multResult interr = pClient.Call("MyMethod.Mult", &Args{2, 7}, &multResult)if err != nil {fmt.Fprintf(os.Stderr, "err : %s\n", err.Error())return}fmt.Fprintf(os.Stdout, "multResult = %d\n", multResult)// 非同步RPCvar divResult DivResultpCall := pClient.Go("MyMethod.Div", &Args{5, 2}, &divResult, nil)if pCall != nil {fmt.Fprintf(os.Stderr, "pCall : %v  %v\n", pCall, pCall.Reply)if replyCall, ok := <-pCall.Done; ok {fmt.Fprintf(os.Stderr, "replyCall : %v  %v\n", replyCall, replyCall.Reply)}}}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.