|
| 1 | +--- |
| 2 | +title: "GLS Feature Usage" |
| 3 | +date: 2023-11-29 |
| 4 | +weight: 11 |
| 5 | +keywords: ["GLS","context"] |
| 6 | +description: "Goroutine local storage for implicitly pass context" |
| 7 | +--- |
| 8 | + |
| 9 | +## Server side enable request context backup |
| 10 | + |
| 11 | +- Option on |
| 12 | + - Use the server option `WithContextBackup`; |
| 13 | + - The first parameter `enable` indicates that the GLS is enabled; |
| 14 | + - The second option, `async`, means to enable asynchronous implicitly pass-through (indicating that the context in the asynchronous call to go func () is also transparent fallback) |
| 15 | + |
| 16 | +```go |
| 17 | +svr := xxx.NewServer(new(XXXImpl), server.WithContextBackup(true, true)) |
| 18 | + |
| 19 | +``` |
| 20 | + |
| 21 | +- Adjust localsession [management options](https://github.com/cloudwego/localsession/blob/main/manager.go#L24) by environment variables |
| 22 | + - First, enable `WithContextBackup` on the Server side. |
| 23 | + - Configure `CLOUDWEGO_SESSION_CONFIG_KEY ``= [{Whether to enable asynchronous pass-through}] [, {Global sharding number}] [, {GC interval}] in environment variables `, all three options are optional, **null means use default value** |
| 24 | + - Ex: `true,10,1h ` means, turn on asynchronous + sharding 10 buckets + 1 hour GC interval |
| 25 | + |
| 26 | +## Client start request context fallback |
| 27 | + |
| 28 | +- Option on |
| 29 | + - Use the client option `WithContextBackup`; |
| 30 | + - The parameter handler represents the backup logic BackupHandler customized by the business. |
| 31 | + |
| 32 | +```go |
| 33 | +func(prev, cur context.Context) (ctx context.Context, backup bool) |
| 34 | + |
| 35 | +``` |
| 36 | + |
| 37 | +- `Prev` parameter represents the context of the backup |
| 38 | +- `Cur` parameter represents the context obtained by the current client |
| 39 | +- `Ctx` return value represents the final context where the user completes processing |
| 40 | +- `Backup` return value indicates whether to continue localsession [built-in fallback backup ](https://github.com/cloudwego/localsession/blob/main/backup/metainfo.go#L54), mainly metainfo Persistent KVS pass-through at present |
| 41 | + |
| 42 | +```go |
| 43 | +var expectedKey interface{} |
| 44 | +cli := xxx.NewClient(serverName, client.WithContextBackup(func(prev, cur context.Context) (ctx context.Context, backup bool) { |
| 45 | + if v := cur.Value(expectedKey); v != nil { |
| 46 | + // expectedKey exists, no need for recover context |
| 47 | + return cur, false |
| 48 | + } |
| 49 | + // expectedKey doesn't exists, need recover context from prev |
| 50 | + ctx = context.WithValue(cur, expectedKey, prev.Value(expectedKey)) |
| 51 | + return ctx, true |
| 52 | +}) |
| 53 | + |
| 54 | +``` |
0 commit comments