Go 语言入门14 – jsonrpc 最简姿势

服务定义

package rpcdemo

import "errors"

// 服务
type DemoService struct {
}

// 参数
type Args struct {
   A, B int
}

// jsonrpc 的服务需要定义为参入参数和传出参数的格式
// 传出参数必须为指针格式
func (e DemoService) DIV(args Args, result *float64) error {
   if args.B == 0 {
      return errors.New("division by zero")
   }

   *result = float64(args.A) / float64(args.B)
   return nil
}

 

服务端

package main

import (
   "github.com/zhaojigang/crawler/rpc"
   "log"
   "net"
   "net/rpc"
   "net/rpc/jsonrpc"
)

func main() {
   // 注册服务
   rpc.Register(rpcdemo.DemoService{})
   // 启动 server
   listener, err := net.Listen("tcp", "127.0.0.1:1234")

   if err != nil {
      panic(err)
   }

   for {
      // 不断连接服务
      conn, err := listener.Accept()
      if err != nil {
         log.Printf("accept error, %v", err)
         continue
      }
      // 使用 Goroutine:ServeConn runs the JSON-RPC server on a single connection.
      go jsonrpc.ServeConn(conn)
   }
}

客户端

package main

import (
   "fmt"
   "github.com/zhaojigang/crawler/rpc"
   "log"
   "net/rpc/jsonrpc"
)

func main() {
   // 连接server并创建jsonrpc-client
   client, err := jsonrpc.Dial("tcp", "127.0.0.1:1234")
   if err != nil {
      log.Printf("create jsonrpc client error")
   }

   var result float64
   // 发起调用
   err = client.Call("DemoService.DIV", rpcdemo.Args{3, 4}, &result)
   if err != nil {
      log.Printf("call error")
   }
   fmt.Println(result)
}

Leave a Comment

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |