Redis 在 Go 后端的应用
Redis 在 Go 后端的典型应用:token 黑名单、速率限制、会话缓存、连接配置和健康检查。
#type / howto
#status / growing
#tech / dev / backend
#resource / go
[!info] related notes
- 相关: JWT 认证
Redis 在 Go 后端的应用
典型场景
Token 黑名单
用户注销后,access token 在 TTL 内仍有效。用 Redis 黑名单使其立即失效:
// 注销时
RedisClient.Set(ctx, "blacklist:"+token, "1", ttl)
// 中间件中检查
exists, _ := RedisClient.Exists(ctx, "blacklist:"+token).Result()
if exists > 0 { /* token 已失效 */ }
速率限制
current, _ := RedisClient.Incr(ctx, key).Result()
if current == 1 {
RedisClient.Expire(ctx, key, window)
}
return current <= int64(limit)
会话缓存
// 存
json, _ := json.Marshal(data)
RedisClient.Set(ctx, "session:"+id, json, ttl)
// 取
val, _ := RedisClient.Get(ctx, "session:"+id).Result()
json.Unmarshal([]byte(val), &dest)
连接配置
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
PoolSize: 10,
MinIdleConns: 2,
DialTimeout: 5 * time.Second,
ReadTimeout: 3 * time.Second,
})
生产注意事项
- 密码必须设置
- 端口不暴露到外网
- 持久化:
appendonly yes - 内存限制:
maxmemory+ 淘汰策略