RPC for Go language _rpc_go language

Source: Internet
Author: User

RPC for a standard library

RPC, remote Procedure call, is an application communication protocol that requests services over a network from a remote computer program without needing to know the details of the underlying network. The simple thing is to call the function of the server like a local function.

The RPC protocol, built on TCP or UDP, or HTTP, allows developers to invoke programs directly on another computer, and developers do not have to write network-communication-related code for the calling process, making it easier to develop applications that include network-distributed programs.

The standard library of the Go language already provides the RPC framework and different RPC implementations.

Here is an example of a server:

Type Echo intfunc (t *echo) Hi (args string, reply *string) error {    *reply = "Echo:" + args    return Nil}func main () {    RPC.} Register (Echo)    RPC. Handlehttp ()    l, E: = Net. Listen ("TCP", ": 1234")    if E! = nil {        log. Fatal ("Listen error:", e)    }    http. Serve (L, Nil)}

Which is rpc.Register used to register the RPC service, the default name is the type name of the object (here is Echo ). If you need to specify a special name, you can use it rpc.RegisterName to register.

The type of the object being registered all methods that meet the following rules are exported to the RPC service interface:

Func (t *t) MethodName (Argtype T1, Replytype *t2) error

The registration must have at least one method to satisfy this feature, or it may fail to register.

It rpc.HandleHTTP is then used to specify the transport protocol for RPC, where the HTTP protocol is used as the carrier for RPC calls. Users can also use the rpc.ServeConn interface to customize their own transport protocols.

The client can call the interface this way Echo.Hi :

Func Main () {    client, err: = RPC. Dialhttp ("TCP", "127.0.0.1:1234")    if err! = Nil {        log. Fatal ("Dialing:", err)    }    var args = "Hello rpc"    var reply string    err = client. Call ("Echo.hi", args, &reply)    if err! = Nil {        log. Fatal ("Arith error:", err)    }    fmt. Printf ("Arith:%d*%d=%d\n", args. A, args. B, Reply)}

The client first uses rpc.DialHTTP a link with the RPC server (the protocol must match).

The client remote function call is then made through the returned object. The name of the function is specified by the client.Call first parameter (is a string).

HTTP-based RPC calls are typically used during debugging, and you can view RPC statistics by default on the Browse "127.0.0.1:1234/debug/rpc" page.

Another example:

Server-side code:

[Plain]View PlainCopy 
  1. Package Main
  2. Import (
  3. "Errors"
  4. "FMT"
  5. "Net/http"
  6. "Net/rpc"
  7. )
  8. Const (
  9. URL = "10.200.7.244:3545"
  10. URL = "127.0.0.1:3545"
  11. )
  12. Type Args struct {
  13. A, B int
  14. }
  15. Type quotient struct {
  16. Quo, Rem int
  17. }
  18. Type Arith int
  19. Func (t *arith) Multiply (args *args, reply *int) error {
  20. *reply = args. A * args. B
  21. return Nil
  22. }
  23. Func (t *arith) Divide (args *args, quo *quotient) error {
  24. If args. B = = 0 {
  25. return errors. New ("Divide by zero!")
  26. }
  27. Quo. Quo = args. A/args. B
  28. Quo. Rem = args. A% args. B
  29. return Nil
  30. }
  31. Func Main () {
  32. Arith: = new (Arith)
  33. Rpc. Register (Arith)
  34. Rpc. Handlehttp ()
  35. ERR: = http. Listenandserve (URL, nil)
  36. If err! = Nil {
  37. Fmt. Println (Err. Error ())
  38. }
  39. }



Client code:

[Plain]View PlainCopy 
  1. Package Main
  2. Import (
  3. "FMT"
  4. "Net/rpc"
  5. )
  6. Const (
  7. URL = "10.200.7.234:3545"
  8. URL = "127.0.0.1:3545"
  9. )
  10. Type Args struct {
  11. A, B int
  12. }
  13. Func Main () {
  14. Client, err: = RPC. Dialhttp ("TCP", URL)
  15. If err! = Nil {
  16. Fmt. Println (Err. Error ())
  17. }
  18. Args: = Args{4, 4}
  19. var reply int
  20. Err = client. Call ("Arith.multiply", &args, &reply)
  21. If err! = Nil {
  22. Fmt. Println (Err. Error ())
  23. } else {
  24. Fmt. Println (Reply)
  25. }
  26. }

[Plain]View PlainCopy 
    1. Client. Call ("Arith.multiply", &args, &reply)

The above method is called synchronously

Code to invoke asynchronously:

[Plain]View PlainCopy 
    1. Quotient: = new (quotient)
    2. Divcall: = client. Go ("Arith.divide", args, "ient, nil)
    3. Replycall: = <-divcall.done



Test:


Two JSON-based RPC calls

In the RPC example above, we used the default HTTP protocol as the transport carrier for RPC calls.

Because of the flaws in the design of the built-in net/rpc package interface, we cannot use jsonrpc such custom encodings as rpc.DialHTTP the underlying protocol. If you need to let the jsonrpc support rpc.DialHTTP function, you need to adjust the RPC interface.

There used to be a Issue2738 for this problem. I have submitted a CL10704046 patch to fix this problem. However, because of the interface to increase RPC, the official is not accepted (because DialHTTP it is easier to rewrite one).

In addition to the transport protocol, you can specify an RPC encoding protocol that is used to encode/program RPC call function parameters and return values. When RPC calls do not specify an encoding protocol, the default is to use the Go language-specific gob encoding protocol.

Because other languages generally do not support the Go Language gob protocol, if a cross-language RPC call is required
Use a common encoding protocol.

The standard library of Go also provides a "net/rpc/jsonrpc" package that provides JSON-encoded-based RPC support.

The server section only needs to use rpc.ServeCodec the specified JSON encoding protocol:

Func Main () {    lis, err: = Net. Listen ("TCP", ": 1234")    if err! = Nil {        return err    }    defer lis. Close ()    srv: = RPC. NewServer ()    if err: = srv. Registername ("Echo", New (Echo)); Err! = Nil {        return err    }    for {        conn, err: = Lis. Accept ()        if err! = Nil {            log. Fatalf ("Lis. Accept ():%v\n ", err)        }        go srv. Servecodec (JSONRPC. NEWSERVERCODEC (conn))    }}

The client part value needs jsonrpc.Dial to rpc.Dial be replaced:

Func Main () {    client, err: = Jsonrpc. Dialhttp ("TCP", "127.0.0.1:1234")    if err! = Nil {        log. Fatal ("Dialing:", err)    }    ...}

If you need to communicate with the jsonrpc go language in other languages, you need to encapsulate a jsonrpc
A matching library.

About jsonrpc The implementation details here will not unfold, interested in the words can refer to this article: Json-rpc:a Tale of interfaces.

Three PROTOBUF-based RPC calls

PROTOBUF is a coding protocol developed by Google. Its advantage is that the encoded data volume is small (not compression algorithm), more suitable for the command of the transmission encoding.

The PROTOBUF official team offers support in several languages Java/c++/python, and the Go language version is supported by the Go team, and other languages are supported by third parties.

The RPC interface can be defined in the PROTOBUF language specification. However, there is no implementation of RPC generation in the Go language and C + + versions of Protobuf.

However, the author developed the RPC implementation PROTORPC on the protobuf basis of the Go language version, and the protoc-gen-go commands provided can generate the corresponding RPC code. Project Address: https://code.google.com/p/protorpc/

The implementation supports the go language and the C + + language and is described in the third-party RPC implementation list on the Protobuf official wiki: https://code.google.com/p/protobuf/wiki/ThirdPartyAddOns#RPC_ Implementations

To use PROTORPC, you need to define the interface () in the proto file first arith.pb/arith.proto :

Package arith;//Go cc_generic_services optionoption cc_generic_services = true;message arithrequest {    optional I Nt32 a = 1;    Optional Int32 b = 2;} Message Arithresponse {    optional int32 val = 1;    Optional Int32 quo = 2;    Optional int32 rem = 3;} Service Arithservice {    RPC multiply (arithrequest) returns (Arithresponse);    RPC Divide (arithrequest) returns (Arithresponse);}

PROTORPC uses cc_generic_services selection to control whether the RPC code is output. Therefore, you need to set cc_generic_services the true .

Then download the Protoc-2.5.0-win32.zip and unzip it to get a protoc.exe compile command.

Then use the following command to get the PROTORPC and corresponding protoc-gen-go plug-ins.

Go get Code.google.com/p/protorpcgo get code.google.com/p/protorpc/protoc-gen-go

Need to be sure protoc.exe and protoc-gen-go.exe both in $PATH . Then run the following command to convert the previous interface file to the go code:

CD ARITH.PB && Protoc--go_out=. Arith.proto

The newly generated file is arith.pb/arith.pb.go .

The following are PROTOBUF-RPC-based servers:

Package Mainimport (    "errors"    "Code.google.com/p/goprotobuf/proto" "    ./ARITH.PB") type Arith intfunc (t * Arith) Multiply (args *arith. Arithrequest, reply *arith. Arithresponse) Error {    reply. Val = Proto. Int32 (args. Geta () * args. GETB ())    return Nil}func (t *arith) Divide (args *arith. Arithrequest, reply *arith. Arithresponse) Error {    if args. GETB () = = 0 {        return errors. New ("Divide by Zero")    }    reply. Quo = Proto. Int32 (args. Geta ()/args. GETB ())    reply. Rem = Proto. Int32 (args. Geta ()% args. GETB ())    return Nil}func main () {    arith. Listenandservearithservice ("TCP", ": 1984", New (Arith))}

Where the name of the import "./arith.pb" is arith , arith.pb/arith.proto defined in the file (these 2 may be different names, be careful when importing).

arith.ArithRequestAnd arith.ArithResponse is the input and output parameters of the RPC interface, which are also arith.pb/arith.proto defined in the file.

There is also a function generated to arith.ListenAndServeArithService start the RPC service. The third parameter of the function is the RPC service object, which must satisfy arith.EchoService the definition of the interface.

The use of the client is also very simple, as long as one arith.DialArithService can be linked:

Stub, client, Err: = Arith. Dialarithservice ("TCP", "127.0.0.1:1984") if err! = Nil {    log. Fatal (' Arith. Dialarithservice ("TCP", "127.0.0.1:1984"): ', err)}defer client. Close ()

arith.DialArithServiceReturns an stub object that has been bound to various methods of RPC and can be called directly (no string is required to specify the method name):

var args arithrequestvar reply arithresponseargs.a = Proto. Int32 (7) args. B = Proto. Int32 (8) If Err = stub. Multiply (&args, &reply); Err! = Nil {    log. Fatal ("Arith error:", err)}fmt. Printf ("Arith:%d*%d=%d", args. Geta (), args. Getb (), reply. Getval ())

Compared to the standard RPC library, the PROTORPC consists of the following advantages:

    1. Use standard PROTOBUF protocol for easy interaction with other languages
    2. Your own protoc-gen-go plug-in can generate RPC code, simplifying the use of
    3. Server registration and calling clients are specific types rather than strings and interface{} can be secured by the compiler
    4. The lower layer uses snappy compressed data to improve efficiency.

The disadvantage is that the process is cumbersome to use than standard RPC (the need to convert proto to go code).

Four C + + calls to the PROTOBUF-RPC service provided by Go

PROTORPC also provides the implementation of the C + + language.

The C + + version is installed as follows:

    1. hg clone https://code.google.com/p/protorpc.cxx/
    2. cd protorpc.cxx
    3. Build with CMake

The C + + version of PROTORPC has protoc.exe extended a
--cxx_outoption to generate the code for the RPC:

${protorpc_root}/protobuf/bin/protoc--cxx_out=. Arith.proto

Note: --cxx_out the code generated by the option has support for serialization and deserialization of XML in addition to RPC support.

The following is a C + + client link to the Go language version of the server:

#include "arith.pb.h" #include <google/protobuf/rpc/rpc_server.h> #include <google/protobuf/rpc/rpc_ Client.h>int Main () {  :: Google::p rotobuf::rpc::client Client ("127.0.0.1", 1234);  Service::arithservice::stub arithstub (&client);:  : Service::arithrequest Arithargs;  :: Service:: Arithresponse arithreply;:  : google::p rotobuf::rpc::error err;  Echoservice.mul  arithargs.set_a (3);  Arithargs.set_b (4);  Err = arithstub.multiply (&arithargs, &arithreply);  if (!err. Isnil ()) {    fprintf (stderr, "arithstub.multiply:%s\n", err. String (). C_STR ());    return-1;  }  if (ARITHREPLY.C ()! =) {    fprintf (stderr, "arithStub.multiply:expected =%d, got =%d\n", N, Arithreply.c ()); 
   
    return-1;  }  printf ("done.\n");  return 0;}
   

For detailed instructions please refer to: readme.md.
For more examples, please refer to: rpcserver.cc
and rpcclient.cc

Five summary

The Go language RPC client is a simple and powerful RPC library. Standard-based RPC libraries we can easily customize our RPC implementations (both the transport Protocol and the serialization Protocol can be customized).

However, in the process of developing PROTORPC also found net/rpc some shortcomings of the package:

    • Built-in HTTP protocol for RPC serialization protocol and transport protocol coupling too tightly, the user-extended protocol cannot support the built-in HTTP transport protocol (because rpc.Server rpc.Client of problems caused by and interface defects)
    • rpc.ServerYou can register only rpc.ServerCodec , but you cannot register a factory function. Instead of jsonrpc.NewServerCodec having to rely on establishing a link ( conn parameter), this results HTTP in a protocol that only supports built gob -in protocols
    • rpc.ClientThe problems and rpc.Server similar

Because GO1 needs to ensure API compatibility, the above-mentioned problems can only be expected to improve in the future Go2.

RPC for Go language _rpc_go language

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.