MCPcopy Create free account
hub / github.com/astercloud/aster / main

Function main

examples/tool-cache/main.go:63–280  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

61}
62
63func main() {
64 fmt.Println("=== 工具缓存示例 ===")
65 fmt.Println()
66
67 // 示例 1: 内存缓存
68 fmt.Println("示例 1: 内存缓存")
69 fmt.Println("---")
70
71 memoryConfig := &tools.CacheConfig{
72 Enabled: true,
73 Strategy: tools.CacheStrategyMemory,
74 TTL: 5 * time.Minute,
75 MaxMemoryItems: 100,
76 }
77
78 memoryCache := tools.NewToolCache(memoryConfig)
79 expensiveTool := &ExpensiveTool{}
80 cachedTool := tools.NewCachedTool(expensiveTool, memoryCache)
81
82 ctx := context.Background()
83 input := map[string]any{"number": 10.0}
84
85 // 第一次执行(无缓存)
86 fmt.Println("第一次执行(无缓存):")
87 start := time.Now()
88 result1, err := cachedTool.Execute(ctx, input, nil)
89 if err != nil {
90 log.Fatalf("Execute failed: %v", err)
91 }
92 duration1 := time.Since(start)
93 fmt.Printf("结果: %v\n", result1)
94 fmt.Printf("耗时: %v\n\n", duration1)
95
96 // 第二次执行(使用缓存)
97 fmt.Println("第二次执行(使用缓存):")
98 start = time.Now()
99 result2, err := cachedTool.Execute(ctx, input, nil)
100 if err != nil {
101 log.Fatalf("Execute failed: %v", err)
102 }
103 duration2 := time.Since(start)
104 fmt.Printf("结果: %v\n", result2)
105 fmt.Printf("耗时: %v\n", duration2)
106 fmt.Printf("性能提升: %.2fx\n\n", float64(duration1)/float64(duration2))
107
108 // 查看统计信息
109 stats := memoryCache.GetStats()
110 fmt.Println("缓存统计:")
111 fmt.Printf(" 命中次数: %d\n", stats.Hits)
112 fmt.Printf(" 未命中次数: %d\n", stats.Misses)
113 fmt.Printf(" 设置次数: %d\n", stats.Sets)
114 fmt.Printf(" 命中率: %.2f%%\n\n", float64(stats.Hits)/float64(stats.Hits+stats.Misses)*100)
115
116 // 示例 2: 文件缓存
117 fmt.Println("示例 2: 文件缓存")
118 fmt.Println("---")
119
120 fileConfig := &tools.CacheConfig{

Callers

nothing calls this directly

Calls 5

ExecuteMethod · 0.95
GetStatsMethod · 0.95
NewToolCacheFunction · 0.92
NewCachedToolFunction · 0.92
PrintfMethod · 0.80

Tested by

no test coverage detected