Redis
go-zero wraps go-redis with connection pooling, metrics, and tracing out of the box.
Configuration
Section titled “Configuration”Redis: Host: 127.0.0.1:6379 Pass: "" Type: node # or "cluster"Initialize
Section titled “Initialize”import "github.com/zeromicro/go-zero/core/stores/redis"
func NewServiceContext(c config.Config) *ServiceContext { return &ServiceContext{ Config: c, Redis: redis.MustNewRedis(c.Redis), }}Common Operations
Section titled “Common Operations”// Set with expiry (seconds)err := rdb.Setex("session:abc123", "userId:42", 3600)
// Getval, err := rdb.Get("session:abc123")
// Atomic countercount, err := rdb.Incr("page:views")
// Distributed locklock := redis.NewRedisLock(rdb, "order:lock:12345")lock.SetExpire(5)if acquired, _ := lock.Acquire(); acquired { defer lock.Release() // critical section}Cache-Aside
Section titled “Cache-Aside”var product Producterr = cache.Take(&product, fmt.Sprintf("product:%d", id), func(v any) error { *v.(*Product) = fetchFromDB(id) return nil})