eko gocache对接Redis报错:store.RedisStore未实现store.StoreInterface
问题原因
这个报错是由gocache版本和依赖的go-redis版本不匹配导致的,不同版本的gocache对应的StoreInterface接口定义、适配的go-redis大版本都有差异:
- 你当前代码用的go-redis v8,仅适配gocache v3及以上版本
- 如果你用的是gocache v2及更早版本,对应的是go-redis v7,接口定义不匹配就会出现
RedisStore没有实现StoreInterface的报错
解决方案
方案1:升级gocache到v3版本(推荐,适配go-redis v8)
- 调整依赖import路径
把原来的import
"github.com/eko/gocache/cache" "github.com/eko/gocache/store"
替换为v3版本路径:
"github.com/eko/gocache/v3/cache" "github.com/eko/gocache/v3/store"
- 修正Set方法调用
gocache v3的Set方法要求第一个参数传入context,把你原来的Set调用:
err := cacheManager.Set("my-key", "my-value", &store.Options{Expiration: 15 * time.Second})
修改为:
err := cacheManager.Set(ctx, "my-key", "my-value", &store.Options{Expiration: 15 * time.Second})
- 更新依赖
执行命令拉取v3版本gocache:go get github.com/eko/gocache/v3@latest
方案2:降级go-redis到v7版本(适配旧版gocache)
如果不想升级gocache,可以把go-redis降到v7版本:
- 把import的
github.com/go-redis/redis/v8替换为github.com/go-redis/redis/v7 - 执行命令拉取v7版本go-redis:
go get github.com/go-redis/redis/v7@latest
修改后可运行的完整代码(方案1)
package main import ( "context" "fmt" "time" "github.com/eko/gocache/v3/cache" "github.com/eko/gocache/v3/store" "github.com/go-redis/redis/v8" ) func main() { ctx := context.Background() redisStore := store.NewRedis(redis.NewClient(&redis.Options{ Addr: "localhost:6379", }), nil) fmt.Println("redisStore", redisStore) cacheManager := cache.New(redisStore) err := cacheManager.Set(ctx, "my-key", "my-value", &store.Options{Expiration: 15 * time.Second}) if err != nil { panic(err) } value, err := cacheManager.Get(ctx, "my-key") switch err { case nil: fmt.Printf("Get the key '%s' from the redis cache. Result: %s", "my-key", value) case redis.Nil: fmt.Printf("Failed to find the key '%s' from the redis cache.", "my-key") default: fmt.Printf("Failed to get the value from the redis cache with key '%s': %v", "my-key", err) } }
内容的提问来源于stack exchange,提问作者chetanspeed511987
相关产品推荐
相关产品推荐

