演示分层状态管理
(ctx context.Context, service *session.InMemoryService, sessionID string)
| 48 | |
| 49 | // 演示分层状态管理 |
| 50 | func demonstrateStateManagement(ctx context.Context, service *session.InMemoryService, sessionID string) { |
| 51 | fmt.Println("📊 State Management Demo") |
| 52 | fmt.Println("========================") |
| 53 | |
| 54 | // 获取会话 |
| 55 | sess, _ := service.Get(ctx, &session.GetRequest{ |
| 56 | AppName: "my-app", |
| 57 | UserID: "user-123", |
| 58 | SessionID: sessionID, |
| 59 | }) |
| 60 | |
| 61 | state := sess.State() |
| 62 | |
| 63 | // 设置不同作用域的状态 |
| 64 | states := map[string]any{ |
| 65 | "app:version": "1.0.0", // 应用级 |
| 66 | "user:preferences": map[string]string{"theme": "dark"}, // 用户级 |
| 67 | "temp:current_task": "processing", // 临时 |
| 68 | "session:message_count": 0, // 会话级 |
| 69 | } |
| 70 | |
| 71 | for key, value := range states { |
| 72 | if err := state.Set(key, value); err != nil { |
| 73 | log.Printf("Error setting %s: %v", key, err) |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | // 读取状态 |
| 78 | fmt.Println("\n📖 Reading states:") |
| 79 | for key := range states { |
| 80 | val, err := state.Get(key) |
| 81 | if err != nil { |
| 82 | log.Printf("Error getting %s: %v", key, err) |
| 83 | continue |
| 84 | } |
| 85 | fmt.Printf(" %s = %v\n", key, val) |
| 86 | } |
| 87 | |
| 88 | // 使用迭代器遍历所有状态 |
| 89 | fmt.Println("\n🔄 Iterating all states:") |
| 90 | for key, value := range state.All() { |
| 91 | scope := getScope(key) |
| 92 | fmt.Printf(" [%s] %s = %v\n", scope, key, value) |
| 93 | } |
| 94 | |
| 95 | fmt.Println() |
| 96 | } |
| 97 | |
| 98 | // 演示事件管理 |
| 99 | func demonstrateEventManagement(ctx context.Context, service *session.InMemoryService, sessionID string) { |