Client

Example:function

In the normal we register methods as services'methods. Methods must follow the below rules:

  • exported method of exported type
  • three arguments, the first is of context.Context, both of exported type for three arguments
  • the third argument is a pointer
  • one return value, of type error
    And rpcx can also register raw functions as services and functions must follow the below rules:

  • the function can be exported or not

  • three arguments, the first is of context.Context, both of exported type for three arguments
  • the third argument is a pointer
  • one return value, of type error
    There is an example.

Server must use RegisterFunction to register a function and provides a service name.

```go server.gotype Args struct { A int B int}

type Reply struct { C int}

func mul(ctx context.Context, args _Args, reply _Reply) error { reply.C = args.A * args.B return nil}

func main() { flag.Parse()

  1. s := server.NewServer()
  2. s.RegisterFunction("a.fake.service", mul, "")
  3. s.Serve("tcp", *addr)

}

  1. Client use the service name and function name to access:
  2. ```go client.go
  3. d := client.NewPeer2PeerDiscovery("tcp@"+*addr, "")
  4. xclient := client.NewXClient("a.fake.service", client.Failtry, client.RandomSelect, d, client.DefaultOption)
  5. defer xclient.Close()
  6. args := &example.Args{
  7. A: 10,
  8. B: 20,
  9. }
  10. reply := &example.Reply{}
  11. err := xclient.Call(context.Background(), "mul", args, reply)
  12. if err != nil {
  13. log.Fatalf("failed to call: %v", err)
  14. }
  15. log.Printf("%d * %d = %d", args.A, args.B, reply.C)

By smallnest updated 2018-12-04 11:47:26