網(wǎng)站首頁 編程語言 正文
超時取消
假設我們希望HTTP請求在給定時間內完成,超時自動取消。
首先定義超時上下文,設定時間返回取消函數(shù)(一旦超時用于清理資源)。調用取消函數(shù)取消后續(xù)操作,刪除子上下文對父的引用。
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*80) defer cancel() req = req.WithContext(ctx)
還可以通過特定時間進行設定:
/ The context will be cancelled after 3 seconds // If it needs to be cancelled earlier, the `cancel` function can // be used, like before ctx, cancel := context.WithTimeout(ctx, 3*time.Second) ???????// Setting a context deadline is similar to setting a timeout, except // you specify a time when you want the context to cancel, rather than a duration. // Here, the context will be cancelled on 2022-11-10 23:00:00 ctx, cancel := context.WithDeadline(ctx, time.Date(2022, time.November, 10, 23, 0, 0, 0, time.UTC))
完整實例如下:
func main() { //定義請求 req, err := http.NewRequest(http.MethodGet, "https://www.baidu.com", nil) if err != nil { log.Fatal(err) } // 定義上下文 ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*80) defer cancel() req = req.WithContext(ctx) // 執(zhí)行請求 c := &http.Client{} res, err := c.Do(req) if err != nil { log.Fatal(err) } defer res.Body.Close() // 輸出日志 out, err := io.ReadAll(res.Body) if err != nil { log.Fatal(err) } log.Println(string(out)) }
超時輸出結果:
2022/12/27 14:36:00 Get "https://www.baidu.com": context deadline exceeded
我們可以調大超時時間,則能正常看到輸出結果。
取消后續(xù)操作
有時請求被取消后,需要阻止系統(tǒng)繼續(xù)做后續(xù)比必要的工作。請看下面用戶發(fā)起的http請求,應用程序接收請求后查詢數(shù)據(jù)庫并返回查詢結果:
正常流程如下:
但如果客戶端取消了請求,如果沒有取消,應用服務和數(shù)據(jù)庫仍然繼續(xù)工作,然后結果卻不能反饋給客戶端。理想狀況為所有下游過程停止,如圖所示:
考慮有兩個相關操作的情況,“相關”的意思是如果一個失敗了,另一個即使完成也沒有意義了。如果已經知道前一個操作失敗了,則希望取消所有相關的操作。請看示例:
func operation1(ctx context.Context) error { // 假設該操作因某種原因而失敗 // 下面模擬業(yè)務執(zhí)行一定時間 time.Sleep(100 * time.Millisecond) return errors.New("failed") } func operation2(ctx context.Context) { // 該方法要么正常執(zhí)行完成 // 要么取消,不再繼續(xù)執(zhí)行 select { case <-time.After(500 * time.Millisecond): fmt.Println("done") case <-ctx.Done(): fmt.Println("halted operation2") } } func main() { // 創(chuàng)建上下文 ctx := context.Background() // 基于上下文創(chuàng)建需求上下文 ctx, cancel := context.WithCancel(ctx) // 在不同協(xié)程中執(zhí)行兩個操作 go func() { err := operation1(ctx) // 如果該方法返回錯誤,則取消該上下文中的后續(xù)操作 if err != nil { cancel() } }() // 實用相同上下文執(zhí)行操作2 operation2(ctx) }
由于我們設置操作2執(zhí)行時間較長,而操作1很快就報錯,因此輸出結果為操作2被取消:
halted operation2
上下文傳值
我們可以實用上下文變量在不同協(xié)程中傳遞值。
假設一個操作需要調用函數(shù)多次,其中用于標識的公共ID需要被 日志記錄,請看示例:
// 定義key,用于保存上下文值的鍵 const keyID = "id" func main() { // 定義上下文值 rand.Seed(time.Now().Unix()) ctx := context.WithValue(context.Background(), keyID, rand.Int()) operation1(ctx) } func operation1(ctx context.Context) { // do some work // we can get the value from the context by passing in the key log.Println("operation1 for id:", ctx.Value(keyID), " completed") operation2(ctx) } func operation2(ctx context.Context) { // do some work // this way, the same ID is passed from one function call to the next log.Println("operation2 for id:", ctx.Value(keyID), " completed") }
這里在main函數(shù)中創(chuàng)建上下文,并采用鍵值對方式存儲id值,從而后續(xù)函數(shù)調用時可以從上下文中獲取該值。如圖所示:
使用context變量在不同操作中傳遞信息非常有用,主要原因包括:
- 線程安全: 一旦設置了上下文鍵,就不能修改它的值,可以使用context.WithValue方法可以設置新的值
- 通用方法: 在Go的官方庫和應用程序中大量使用上下文傳遞數(shù)據(jù),我們當然最好也使用這種模式
原文鏈接:https://blog.csdn.net/neweastsun/article/details/128458477
相關推薦
- 2022-09-03 Nginx代理Redis哨兵主從配置的實現(xiàn)_nginx
- 2022-08-30 cvc-complex-type.2.4.a: 發(fā)現(xiàn)了以元素 ‘base-extension‘ 開頭
- 2022-03-29 Python雙端隊列實現(xiàn)回文檢測_python
- 2022-06-10 Docker部署springboot項目到騰訊云的實現(xiàn)步驟_docker
- 2022-06-16 golang?gorm錯誤處理事務以及日志用法示例_Golang
- 2022-07-20 Python實現(xiàn)向PPT中插入表格與圖片的方法詳解_python
- 2022-03-16 C++冒泡排序與選擇排序詳解_C 語言
- 2022-02-28 el-dialog 的關閉事件執(zhí)行兩次
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支