golang RPC通信中,有时候就怕读写hang住。

那是否可以设置读写超时呢?

1.方案一: 设置连接的读写超时

1.1 client

RPC通信基于底层网络通信,可以通过设置connection的读写超时时间,达到RPC读写超时的目的。更多细节可参考golang网络通信超时设置.

下面以client端的读超时为例,介绍设置方法。

server端和client端代码如下。

server

一个简单的json RPC server。

package main

import (
"fmt"
"log"
"net"
"net/rpc"
"net/rpc/jsonrpc"
"time"
) type Counter struct {
Sum int
} func (this *Counter) Add(i int, r *int) error {
//sleep
time.Sleep(3*time.Second) if i < 0 {
return fmt.Errorf("data format incorrect")
} this.Sum += i
*r = this.Sum
log.Printf("i: %v\n", i)
return nil
} func NewJsonRpcSocketServer() { rpc.Register(new(Counter)) l, err := net.Listen("tcp", ":3333")
if err != nil {
log.Printf("Listener tcp err: %s", err)
return
} for {
log.Println("waiting...")
conn, err := l.Accept()
if err != nil {
log.Printf("accept connection err: %s\n", conn)
continue
} go jsonrpc.ServeConn(conn)
} } func main() {
NewJsonRpcSocketServer()
}

client

json RPC client。

连接建立后,会设置connection的读超时时间。

package main

import (
"log"
"net"
"net/rpc/jsonrpc"
"time"
) func main() { NewJsonRpcSocketClient()
} func NewJsonRpcSocketClient() {
timeout := time.Second*30
conn, err := net.DialTimeout("tcp", "127.0.0.1:3333", timeout)
if err != nil {
log.Printf("create client err:%s\n", err)
return
}
defer conn.Close() // timeout
readAndWriteTimeout := 2*time.Second
err = conn.SetDeadline(time.Now().Add(readAndWriteTimeout))
if err != nil {
log.Println("SetDeadline failed:", err)
} client := jsonrpc.NewClient(conn) var reply int err = client.Call("Counter.Add", 2, &reply)
if err != nil {
log.Println("error:", err, "reply:", reply)
return
} log.Printf("reply: %d, err: %v\n", reply, err) }

client输出:

2019/05/12 22:52:57 error: read tcp 127.0.0.1:55226->127.0.0.1:3333: i/o timeout reply: 0

1.2 server

通常情况下,RPC server端的代码如下:

    server := rpc.NewServer()
... ....
for {
conn, err := l.Accept()
if err != nil {
log.Println("listener accept fail:", err)
time.Sleep(time.Duration(100) * time.Millisecond)
continue
} // timeout
timeout := 10*time.Second
conn.SetDeadline(time.Now().Add(timeout)) go server.ServeCodec(jsonrpc.NewServerCodec(conn))
}

这样,如果设置超时,只有效的影响一次。

对于server来说,都是多次读写。所以,暂时没有方法设置。

2.方案二:定时器

通过定时器的方式,如果RPC调用在指定时间内没有完成,触发定时器,返回超时错误,关闭连接。

2.1 client端

func  RpcCall(method string, args interface{}, reply interface{}) error {
... ... timeout := time.Duration(10 * time.Second)
done := make(chan error, 1) go func() {
err := rpcClient.Call(method, args, reply)
done <- err
}() select {
case <-time.After(timeout):
log.Printf("[WARN] rpc call timeout %v => %v", rpcClient, RpcServer)
rpcClient.Close()
return fmt.Errorf("timeout")
case err := <-done:
if err != nil {
rpcClient.Close()
return err
}
} return nil
}

2.2 server端

无论是gobServerCodec 或者 jsonrpc ,都是实现了ServerCodec接口。

gobServerCodec文件路径:/usr/local/go/src/net/rpc/server.go

jsonrpc文件路径:/usr/local/go/src/net/rpc/server.go

要给server端RPC读写加上超时机制,需要重新定义ServerCodec接口,加上超时的控制。

// A ServerCodec implements reading of RPC requests and writing of
// RPC responses for the server side of an RPC session.
// The server calls ReadRequestHeader and ReadRequestBody in pairs
// to read requests from the connection, and it calls WriteResponse to
// write a response back. The server calls Close when finished with the
// connection. ReadRequestBody may be called with a nil
// argument to force the body of the request to be read and discarded.
type ServerCodec interface {
ReadRequestHeader(*Request) error
ReadRequestBody(interface{}) error
// WriteResponse must be safe for concurrent use by multiple goroutines.
WriteResponse(*Response, interface{}) error Close() error
}

目前,已经有现成的实现方式,可参考Golang标准库RPC实践及改进

3.参考

Does RPC have a timeout mechanism?

net/rpc: expected Timeout based alternatives to functions for rpc.Dial, rpc.DialHTTP, rpc.DialHTTPPath [proposal]. #15236

golang RPC通信读写超时设置的更多相关文章

  1. golang网络通信超时设置

    网络通信中,为了防止长时间无响应的情况,经常会用到网络连接超时.读写超时的设置. 本文结合例子简介golang的连接超时和读写超时设置. 1.超时设置 1.1 连接超时 func DialTimeou ...

  2. RPC通信功能实现

    Table of Contents RPC通信功能实现 配置參数 调用方法 RPC通信功能实现 HBase的RPC通信功能主要基于Protobuf和NIO这两个组件来实现.在通信管道上选择的是prot ...

  3. [转]JDBC如何进行超时设置

    文档来源:https://jingyan.baidu.com/article/fc07f98922615a12ffe519ce.html 恰当的JDBC超时设置能够有效地减少服务失效的时间.本文将对数 ...

  4. RPC通信原理(未完,先睡觉)

    一 背景 OpenStack 各组件之间是通过 REST 接口进行相互通信,比如Nova.Cinder.Neutron.Glance直间的通信都是通过keystone获取目标的endpoint,即ap ...

  5. 深入理解JDBC的超时设置

    恰当的JDBC超时设置能够有效地减少服务失效的时间.本文将对数据库的各种超时设置及其设置方法做介绍. 真实案例:应用服务器在遭到DDos攻击后无法响应 在遭到DDos攻击后,整个服务都垮掉了.由于第四 ...

  6. JDBC超时设置【转】

    恰当的JDBC超时设置能够有效地减少服务失效的时间.本文将对数据库的各种超时设置及其设置方法做介绍. 真实案例:应用服务器在遭到DDos攻击后无法响应 在遭到DDos攻击后,整个服务都垮掉了.由于第四 ...

  7. Spring Cloud 系列之 Dubbo RPC 通信

    Dubbo 介绍 官网:http://dubbo.apache.org/zh-cn/ Github:https://github.com/apache/dubbo 2018 年 2 月 15 日,阿里 ...

  8. Linux串口中的超时设置

    在Linux下使用串口通信时,默认的阻塞模式是不实用的.而采用select或epoll机制的非阻塞模式,写代码有比较麻烦.幸好Linux的串口自己就带有超时机制. Linux下使用termios.h中 ...

  9. PHP与Golang如何通信?

    PHP与Golang如何通信? 最近遇到的一个场景:php项目中需要使用一个第三方的功能(结巴分词),而github上面恰好有一个用Golang写好的类库.那么问题就来了,要如何实现不同语言之间的通信 ...

随机推荐

  1. 4.pca与梯度上升法

    (一)什么是pca pca,也就是主成分分析法(principal component analysis),主要是用来对数据集进行降维处理.举个最简单的例子,我要根据姓名.年龄.头发的长度.身高.体重 ...

  2. primer看完了

    放假这将近十天吧,终于把C++ Primer中文版第五版大致看完了,然而第四部分(高级主题)还是没有看,感觉那是需要有足够的项目经验再看. 另外,看一遍肯定不够,忘得也会很快,我十分确认今后还会很多次 ...

  3. Summer training round2 #9(Training28)

    A:签到题 C:模拟搜索题 #include <bits/stdc++.h> #include <cstring> #include <iostream> #inc ...

  4. LCA-tarjan understand

    首先是最近公共祖先的概念(什么是最近公共祖先?): 在一棵没有环的树上,每个节点肯定有其父亲节点和祖先节点,而最近公共祖先,就是两个节点在这棵树上深度最大的公共的祖先节点. 换句话说,就是两个点在这棵 ...

  5. ES添加文档 踩坑之 —— The number of object passed must be even but was [1]

    读取文件,获取json格式的数据doc, 然后使用 bulkRequestBuilder.add(client.prepareIndex(index, type, id).setSource(doc) ...

  6. win redis安装

    一.下载windows版本的Redis 去官网找了很久,发现原来在官网上可以下载的windows版本的,现在官网以及没有下载地址,只能在github上下载,官网只提供linux版本的下载 官网下载地址 ...

  7. 新建swap分区

    1.在一块新盘上创建一个主分区,大小为1G大小. 2.将该硬盘数据变更为82(swap),并进行保存 3.查看是否已经将新建分区更改成了swap分区 4.将/dev/sdb2的标签设置为swap-sd ...

  8. 创建Windows任务计划定时调用网页执行任务(通过Windows PowerShell的Invoke-WebRequest实现)

    前言:项目中使用RoadFlow工作流,设置超时自动提交功能,自动提交功能已有现成的网页可实现(http://127.0.0.1/WorkFlowRun/AutoSubmit),现需创建Windows ...

  9. 处理并解决mysql8.0 caching-sha2-password问题,开启远程访问

    原文:https://blog.csdn.net/u010026255/article/details/80062153 启动mysql服务:service mysqld start ALTER US ...

  10. 对abel 转译 class 过程的研究----------------------引用

    作为当下最流行的 JavaScript 编译器,Babel 替我们转译 ECMAScript 语法,而我们不用再担心如何进行向后兼容. 零.前言 虽然在 JavaScript 中对象无处不在,但这门语 ...