Golang-gob and RPC

Source: Internet
Author: User

Today and everyone talk about how to use RPC,RPC data transmission in Golang GOB encoding, so first talk about Gob, don't worry, even if you have not touched the GOB and RPC, as long as the RPC is the Chinese is a remote procedure call, the rest I can give you understand (take you get the introduction does not pack you proficient)!

GOB of data structure coding

Gob all called: Go binary

Golang comes with a data structure serialization encoding/decoding tool, which means that gob can say that a data structure in go is serialized into something, and can be deserialized! Serialization into what we see later, whether it is to become a string, into a binary stream, into what first, anyway, the function is serialization.

Gob use we need to pay attention to encoder and decoder objects, as the name implies, one is encoded when used, one is decoded when used, we look at how to get these two objects first:

So it is clear that these two functions need to be called to get the encoder and decoder objects. Note that the parameter here is IO. Writer and Io.reader interface types, we introduced these two interfaces in the previous lecture, so the parameters needed here are the objects that implement the Io.writer and Io.reader interface types.

One of the main methods of encoder and decoder were:

See here we can get the following conclusions:

Gob uses IO. Writer interface, the Newencoder () function is used to create the Encoder object by calling the Encode () method to implement the encoding operation; Reader interface, create a Decoder object through the Newdecoder () function and call the Decode () method to complete the decoding operation!

Next we try to use this encoder and decoder, we can easily get started gob, to take a look at the first example

Example 1: Data structure and bytes. Conversion between buffer (encoded into a byte slice)

 1package main 2 3import  (4     "bytes" 5     "FMT" 6      "Encoding/gob" 7     "io" 8) 910//prepare the encoded data 11type p struct {12     X, Y, Z INT13    NAME    STRING14} 1516//structure of receiving decoding results 17type q struct {18    x, y *int3219     name string20}2122func main ()  {23    //Initializes a data 24     data := P{3, 4, 5,  "Cloudgeek"}25    //encoded BUF byte slice 26 The     buf := encode (data) 27    //is used to receive decoded data 28     var q *q29    //decoding Operation 30    q = decode (BUF) 31     //"Cloudgeek":  {3,4}32    fmt. Printf ("%q: {%d,%d}\n",  q.name,&nbsP;*Q.X, *Q.Y) 3334}3536func encode (data interface{})  *bytes. The Buffer {37    //buffer type implements the Io.writer interface 38    var buf  bytes. buffer39    //Get encoder 40    enc := gob. Newencoder (&BUF) 41    //calls the Encode method of the encoder to encode the data data42    enc. Encode (data) 43    //encoded results are placed in BUF 44    return &buf45}4647func  decode (data interface{})  *q {48    d := data. ( Io. Reader) 49    //get a decoder, the parameters need to implement IO. Reader interface 50    dec := gob. Newdecoder (d) 51    var q q52    //calls the decoder's Decode method to decode the data, Q to receive the 53    DEC. Decode (&q) 54    return &q55}

Example 2: Data structure to the serialization and deserialization of a file

 1package main 2 3import  (4     "Encoding/gob" 5     "OS" 6      "FMT" 7) 8 9//test data type 10type address struct {11    city     string12    country string13}1415//the path of data storage after serialization 16var  Filepath string1718func main ()  {19    filePath =  "./address.gob" 20    encode () 21    pa := decode () 22     Fmt. Println (*PA)  //{chengdu china}23}2425//writes the data serial number to the file 26func encode ()  {27     pa := &address{"Chengdu",  "China"}28    //open file, new 29  when not present    file, _ := os. OpenFile (Filepath, os. O_create|os. o_wronly, 0666) 30    defer file. Close () 3132    //encode write to this file 33    enc : = gob. Newencoder (file) 34    enc. Encode (PA) 35}3637//reading data from a file and deserializing 38func decode ()  *Address {39    file,  _ := os. Open (FilePath) 40    defer file. Close () 4142    var pa address43    //decode operation 44     dec := gob. Newdecoder (file) 45    dec. Decode (&PA) 46    return &pa47}

The above 2 examples are not difficult, I removed the error handling and other code, as far as possible to comment on each piece of code, patiently read these 2 examples should be able to appreciate the gob encode and decode essence.

Understanding what GOB is based on, if you need to use GOB development, it is recommended to take a detailed look at the official documentation to learn more about the details: https://golang.org/pkg/encoding/gob/

Ii. Getting Started with RPC in Golang

If you have not done the RPC communication-based development work, directly to the Internet to check RPC related knowledge point is likely to face a mask, rest API So good understanding, an HTTP request in the past, RPC why did back to the matter, do not understand ah ...

So I would not like most tutorials in order to pursue the details or show their own technology more than the ox to write a long example, pull a bunch of professional concepts, we first the quickest way to experience the feeling of RPC call!

RPC Service side

  1package main 2 3import  (4     "NET" 5     "NET/RPC" 6      "Net/http" 7) 8 9type args struct {10    a, b  int11}1213//defines an arithmetic type, which is actually int14type arith int1516//the method of multiplying is bound to the Arith type, regardless of why this is the form 17func  (t  *arith)  multiply (args *args, reply *int)  error {18     *reply = args. A * args. B19    return nil20}2122func main ()  {23    // Get a pointer instance of type Arith 24    arith := new (arith) 25    //Register to RPC service 26     rpc. Register (Arith) 27    //hangs on the HTTP service 28    rpc. Handlehttp () 29    //began to listen for 30    l, _ := net. Listen ("TCP",  ": 1234") 31    http. Serve (L, nil) +  

RPC Client

 1package main 2 3import ( 4    "net/rpc" 5    "fmt" 6) 7 8type Args struct { 9    A, B int10}1112func main() {13    //连接服务器端,创建一个client14    client, _ := rpc.DialHTTP("tcp", "127.0.0.1:1234")15    args := &Args{7, 8}16    var reply int17    //通过Call方法调用Arith类型的Multiply方法,注意形参18    client.Call("Arith.Multiply", args, &reply)19    //得到调用结果,输出Arith: 7*8=5620    fmt.Printf("Arith: %d*%d=%d\n", args.A, args.B, reply)21}

The above 2 procedures are very brief, perhaps you do not understand the details, but also please be patient, this time you should be able to have an RPC call concept, the client directly called the server side of a function to pass the past parameter list and receive the return value of the object, get the call result.

Third, some details of RPC

Let's look at some RPC-related details

The first method that can be called by RPC should look like this:

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

Probably explain:

    • The function must be exportable (capitalize in the first letter)
    • You must have two parameters for the exported type, the first parameter to receive the parameter, the second parameter to the result parameter returned to the client, and the second argument to be the pointer type
    • Function must also have a return value error
    • T1, T2 can be ENCODING/GOB encoded

See here you should have a certain understanding of the role of RPC, go RPC packet usage is simply to prepare a type, bind a bunch of conforming methods, and then register to the RPC service, listen to the client connection, The call method provided by the client through the RPC package can be called to the server-registered method. For more details, you can look at the official document: https://golang.org/pkg/net/rpc/

124 Reads

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.