Go语言Redis缓存高性能缓存实现1. Redis客户端package cache import ( context time github.com/redis/go-redis/v9 ) type RedisCache struct { client *redis.Client } func NewRedisCache(addr, password string, db int) (*RedisCache, error) { client : redis.NewClient(redis.Options{ Addr: addr, Password: password, DB: db, }) ctx : context.Background() if err : client.Ping(ctx).Err(); err ! nil { return nil, err } return RedisCache{client: client}, nil } func (c *RedisCache) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error { return c.client.Set(ctx, key, value, expiration).Err() } func (c *RedisCache) Get(ctx context.Context, key string) (string, error) { return c.client.Get(ctx, key).Result() } func (c *RedisCache) Delete(ctx context.Context, key string) error { return c.client.Del(ctx, key).Err() } func (c *RedisCache) Exists(ctx context.Context, key string) (bool, error) { count, err : c.client.Exists(ctx, key).Result() return count 0, err }2. 总结Redis是最流行的内存数据库之一适合作为高性能缓存使用。
Go语言Redis缓存:高性能缓存实现
发布时间:2026/5/17 10:57:05
Go语言Redis缓存高性能缓存实现1. Redis客户端package cache import ( context time github.com/redis/go-redis/v9 ) type RedisCache struct { client *redis.Client } func NewRedisCache(addr, password string, db int) (*RedisCache, error) { client : redis.NewClient(redis.Options{ Addr: addr, Password: password, DB: db, }) ctx : context.Background() if err : client.Ping(ctx).Err(); err ! nil { return nil, err } return RedisCache{client: client}, nil } func (c *RedisCache) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error { return c.client.Set(ctx, key, value, expiration).Err() } func (c *RedisCache) Get(ctx context.Context, key string) (string, error) { return c.client.Get(ctx, key).Result() } func (c *RedisCache) Delete(ctx context.Context, key string) error { return c.client.Del(ctx, key).Err() } func (c *RedisCache) Exists(ctx context.Context, key string) (bool, error) { count, err : c.client.Exists(ctx, key).Result() return count 0, err }2. 总结Redis是最流行的内存数据库之一适合作为高性能缓存使用。