加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang RPC调用例子程序(实现超时机制)

发布时间:2020-12-16 18:19:59 所属栏目:大数据 来源:网络整理
导读:package mainimport ( "fmt" "log" "net" "net/rpc" "time" )func main() { log .SetFlags (log .Lshortfile | log .Lmicroseconds ) log .Println ( "=======begin====== " ) testRpc() time .Sleep (time .Second * 2 ) log .Println ( "=======end======
package main

import (
    "fmt"
    "log"
    "net"
    "net/rpc"
    "time"
)

func main() {
    log.SetFlags(log.Lshortfile | log.Lmicroseconds)
    log.Println("=======begin====== ")

    testRpc()

    time.Sleep(time.Second * 2)
    log.Println("=======end====== ")
}

type Args struct {
    A,B int
}

type Math int

func (t *Math) Division(args *Args,reply *int) error {
    if args.B == 0 {
        return fmt.Errorf("args.B == 0")
    }

    *reply = args.A / args.B
    //time.Sleep(time.Second * 3)
    return nil
}

func testRpc() {
    newServer := rpc.NewServer()
    newServer.Register(new(Math))
    server,_ := net.Listen("tcp","127.0.0.1:1234") // any available address
    go newServer.Accept(server)

    time.Sleep(1 * time.Second)
    conn,_ := net.DialTimeout("tcp","127.0.0.1:1234",time.Second)
    defer conn.Close()
    conn.SetReadDeadline(time.Now().Add(time.Second * 1))

    client := rpc.NewClient(conn)
    defer client.Close()

    reply := new(int)
    callErr := client.Call("Math.Division",&Args{8,2},reply)
    log.Println("call err:",callErr,"reply:",*reply)
}

  • 采用低层次的api,可以设置一些超时时间,比如连接超时、读写超时等
  • rpc要对返回值进行判断,不仅仅判断远程调用的错误吗,还有其他一些异常情况的判断,包括调用超时,service没有注册,没有找到相应的method等。

args.B == 0 rpc: can’t find service Math_test.Divisio rpc: can’t find method Math.Division_test read tcp 127.0.0.1:30624->127.0.0.1:1234: i/o timeout

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读