ctx控制超时的使用
cancel
package main
import (
"context"
"fmt"
"time"
)
func gen(ctx context.Context) <-chan int {
dst := make(chan int)
n := 1
go func() {
for {
select {
case <-ctx.Done():
fmt.Println("i exited")
return // returning not to leak the goroutine
case dst <- n:
n++
}
}
}()
return dst
}
func test() {
// gen generates integers in a separate goroutine and
// sends them to the returned channel.
// The callers of gen need to cancel the context once
// they are done consuming generated integers not to leak
// the internal goroutine started by gen.
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // cancel when we are finished consuming integers
intChan := gen(ctx)
for n := range intChan {
fmt.Println(n)
if n == 5 {
break
}
}
}
func main() {
test()
time.Sleep(time.Hour)
}
deadline
package main
import (
"context"
"fmt"
"time"
)
func main() {
d := time.Now().Add(1000 * time.Millisecond)
ctx, cancel := context.WithDeadline(context.Background(), d)
// Even though ctx will be expired, it is good practice to call its
// cancelation function in any case. Failure to do so may keep the
// context and its parent alive longer than necessary.
defer cancel()
select {
case <-time.After(1 * time.Second):
fmt.Println("overslept")
case <-ctx.Done():
fmt.Println(ctx.Err())
}
}
timeout
package main
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"time"
)
type Result struct {
r *http.Response
err error
}
func process() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
tr := &http.Transport{}
client := &http.Client{Transport: tr}
c := make(chan Result, 1)
req, err := http.NewRequest("GET", "http://www.baidu.com", nil)
if err != nil {
fmt.Println("http request failed, err:", err)
return
}
go func() {
resp, err := client.Do(req)
pack := Result{r: resp, err: err}
c <- pack
}()
select {
case <-ctx.Done():
tr.CancelRequest(req)
res := <-c
fmt.Println("Timeout! err:", res.err)
case res := <-c:
defer res.r.Body.Close()
out, _ := ioutil.ReadAll(res.r.Body)
fmt.Printf("Server Response: %s", out)
}
return
}
func main() {
process()
}
value
package main
import (
"context"
"fmt"
)
func process(ctx context.Context) {
ret,ok := ctx.Value("trace_id").(int)
if !ok {
ret = 21342423
}
fmt.Printf("ret:%d\n", ret)
s , _ := ctx.Value("session").(string)
fmt.Printf("session:%s\n", s)
}
func main() {
ctx := context.WithValue(context.Background(), "trace_id", 13483434)
ctx = context.WithValue(ctx, "session", "sdlkfjkaslfsalfsafjalskfj")
process(ctx)
}
ctx控制超时的使用的更多相关文章
- 并发包之Future:代码级控制超时时间
先谢Doug Lea. 使用场景: 最近在做webservice调用的时候,发现一个问题,对方的webservice接口很不稳定,所以在获取的数据时候经常要等待很久才能把数据全部拉回来,甚至有时候直接 ...
- 【转】在Spring中基于JDBC进行数据访问时怎么控制超时
http://www.myexception.cn/database/1651797.html 在Spring中基于JDBC进行数据访问时如何控制超时 超时分类 超时根据作用域可做如下层级划分: Tr ...
- 在Spring中基于JDBC进行数据访问时如何控制超时
超时分类 超时根据作用域可做如下层级划分: Transaction Timeout > Statement Timeout > JDBC Driver Socket Timeout Tra ...
- ajax请求web容器控制超时
1.项目用到超时控制,针对ajax请求超时,可以参照如下解决方案 tomcat容器 web.xml 中配置 <session-config> <session-timeout> ...
- PHP超时处理全面总结
[ 概述 ] 在PHP开发中工作里非常多使用到超时处理到超时的场合,我说几个场景: 1. 异步获取数据如果某个后端数据源获取不成功则跳过,不影响整个页面展现 2. 为了保证Web服务器不会因为当个页面 ...
- PHP超时处理全面总结(转)
[ 概述 ] 在PHP开发中工作里非常多使用到超时处理到超时的场合,我说几个场景: 1. 异步获取数据如果某个后端数据源获取不成功则跳过,不影响整个页面展现 2. 为了保证Web服务器不会因为当个页面 ...
- 转:PHP超时处理全面总结
原文来自于:http://wulijun.github.io/2012/08/08/php-timeout-summary.html 概述 在PHP开发工作里非常多使用到超时处理的场合,我说几个场景: ...
- dubbo(九):timeout超时机制解析
在网络请求时,总会有各种异常情况出现,我们需要提前处理这种情况.在完善的rpc组件dubbo中,自然是不会少了这一层东西的.我们只需要通过一些简单的配置就可以达到超时限制的作用了. dubbo的设计理 ...
- delphi tidhttp 超时设置无效的解决方法
现在delphi都发布到xe8了,tidhttp还有缺陷,那就是超时设置在没有网络或者连不上服务器的时候是无效的,不管你设置为多少都要10-20秒.connectTimeout和readTimeout ...
随机推荐
- LeetCode 1259. Handshakes That Don't Cross - Java - DP
题目链接:https://leetcode-cn.com/problems/handshakes-that-dont-cross/ You are given an even number of pe ...
- 【leetcode-97 动态规划】 交错字符串
(1过,调试很久) 给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的. 示例 1: 输入: s1 = "aabcc", s2 = " ...
- WPF 的 VisualBrush 只刷新显示的视觉效果,不刷新布局范围
原文:WPF 的 VisualBrush 只刷新显示的视觉效果,不刷新布局范围 WPF 的 VisualBrush 可以帮助我们在一个控件中显示另一个控件的外观.这是非常妙的功能. 但是本文需要说其中 ...
- MVC中常用的返回值方法
我们上边所看到的Action都是return View();我们可以看作这个返回值用于解析一个aspx文件.而它的返回类型是ActionResult如 public ActionResult Inde ...
- ASP.NET SignalR 系列(二)之项目创建
一.项目环境 IDE:VisualStudio 2015 SignalR 2.3.0 JQuery版本1.10.1 ,要求必须1.6.4以上 .net Framework 4.6 SignalR2.0 ...
- sparksql读取hive数据报错:java.lang.RuntimeException: serious problem
问题: Caused by: java.util.concurrent.ExecutionException: java.lang.IndexOutOfBoundsException: Index: ...
- in __init__ self._traceback = tf_stack.extract_stack()的一个原因
这样就会出错,原因在于函数返回为三个变量,若直接向写入函数那样运用sess.run()得到,就会导致错误. sess=tf.Session() sess.run(tf.initialize_all_v ...
- 自学Python编程的第八天----------来自苦逼的转行人
2019-09-18-21:11:24(初学者不会学博客,望大家见谅见谅) 今天学的内容是有关list..dict.set集合的使用方法和注意事项 list和dict在循环中不可删,而且list在迭代 ...
- 安装VMware14可能出现的问题
未能提取文件 安装程序未能提取安装vmware workstation所必须的文件 在没有关闭这个弹框的前提下,Win+R输入%temp%,找到以~setup结尾的文件夹,双击下面的临时文件VMwar ...
- iOS之集成GoogleMap定位、搜索注意事项
简介: 最近花了些时间看了GoogleMap官方文件并集成到国际版app中,网上关于GoogleMap for iOS的讲解相对Android来说少一点,比较有帮助的几乎全是英文文档.下面是我开发过程 ...