go连接mysql的超时异常

看着奢扣 2019-08-19 12:06:08
go通过exec.Command连接mysql, 希望10秒钟还是连不上报timeout
如何设计
...全文
289 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
qybao 2019-08-19
  • 打赏
  • 举报
回复
用cotext控制timeout就好了,for example

import (
"os/exec"
"context"
)

func main() {
ctx, cancel := context.WithTimeout(context.TODO(), time.Second * 10) //10秒timeout
defer cancel()
t1 := time.Now().Unix()
out, err := exec.CommandContext(ctx, "sleep", "20").Output() //例子,sleep20秒
//out, err := exec.CommandContext(ctx, "/usr/local/bin/mysql/mysql -u root").Output()
t2 := time.Now().Unix()
if err != nil {
fmt.Printf("err=%v\n", err)
}
fmt.Printf("out=%v, time=%v\n", out, t2-t1)
}

2,190

社区成员

发帖
与我相关
我的任务
社区描述
go语言学习与交流版
社区管理员
  • go语言社区
  • Freeman Z
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧