Skip to content

Commit 5b28e2a

Browse files
committed
doc: upload file Goroutine-Local-Storage 功能使用
1 parent 028dc64 commit 5b28e2a

File tree

1 file changed

+67
-0
lines changed
  • content/zh/docs/kitex/Tutorials/advanced-feature

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
---
2+
title: "Goroutine-Local-Storage 功能使用"
3+
date: 2023-11-29
4+
weight: 1
5+
keywords: ["Goroutine-Local-Storage 功能使用"]
6+
description: ""
7+
---
8+
9+
## Introduction
10+
11+
GLS 用于存储 goroutine 内的上下文信息,作用类似于 context。相比 context 有如下优势:
12+
13+
1. **不需要显式传递**,在任意函数位置都可调用 CurSession() 获取上下文(如果有)
14+
2. **可以在父子****协程****间传递**(需要开启选项)
15+
16+
框架目前主要使用 GLS 进行 context 备份,以避免用户误传 context 导致链路透传信息(如 logid、metainfo 等)丢失
17+
18+
## Server 端开启请求 context 备份
19+
20+
- 选项开启
21+
- 使用 server option WithContextBackup;
22+
- 第一个参数 enable 表示开启备份功能;
23+
- 第二个选项 async 表示开启异步隐式透传(表示对 go func() 异步调用中的 context 也进行透明兜底)
24+
25+
```go
26+
```
27+
28+
svr := xxx.NewServer(new(XXXImpl), server.WithContextBackup(true, true))
29+
30+
```
31+
32+
- 环境变量调整 localsession [管理选项](https://github.com/cloudwego/localsession/blob/main/manager.go#L24)
33+
1. 首先在【Server 端开启WithContextBackup】
34+
2. 环境变量中配置 `CLOUDWEGO_SESSION_CONFIG_KEY``=[{是否开启异步透传}][,{全局分片数}][,{GC间隔}]`,三个选项都为可选,**空表示使用默认值**
35+
1. ex: `true,10,1h `表示 开启异步+分片10+1小时GC间隔
36+
37+
## Client 端开启请求 context 兜底
38+
39+
- 选项开启
40+
- 使用 client option `client.``WithContextBackup``(handler)`;
41+
- 参数 handler 表示业务自定义的备份逻辑 BackupHandler,其签名为
42+
```go
43+
func(prev, cur context.Context) (ctx context.Context, backup bool)
44+
45+
```
46+
47+
```
48+
- `p``rev` 参数表示备份的 context
49+
- `c``ur` 参数表示当前 client 拿到的 context
50+
- `c``tx` 返回值表示用户处理完成的最终 context
51+
- `b``ackup` 返回值表示是否继续进行 localsession[ 内置的兜底备份](https://github.com/cloudwego/localsession/blob/main/backup/metainfo.go#L54),当前主要是 metainfo Persistent KVS 的透传
52+
```go
53+
```
54+
55+
var expectedKey interface{}
56+
cli := client.New(serverName, client.WithContextBackup(func(prev, cur context.Context) (ctx context.Context, backup bool) {
57+
if v := cur.Value(expectedKey); v != nil {
58+
// expectedKey exists, no need for recover context
59+
return cur, false
60+
}
61+
// expectedKey doesn't exists, need recover context from prev
62+
ctx = context.WithValue(cur, expectedKey, prev.Value(expectedKey))
63+
return ctx, true
64+
})
65+
66+
```
67+
```

0 commit comments

Comments
 (0)