feat(redis): 增加 Pub/Sub 封装
通知推送需要跨进程广播。Client 增加 Publish 与 Subscribe。 Subscribe 先等 Receive 确认订阅生效再返回。否则存在"订阅已返回、第一条消息已发出"的丢消息窗口。失败时先关闭 PubSub 再返回错误。 客户端未初始化时返回错误,不 panic。
This commit is contained in:
@@ -103,6 +103,30 @@ func (c *Client) Unlock(ctx context.Context, key string, token string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Publish 向频道发布一条消息。频道名由调用方用 Key 统一加前缀,
|
||||
// 同一 Redis 上的多套环境才不会互相收到对方的消息。
|
||||
func (c *Client) Publish(ctx context.Context, channel string, payload []byte) error {
|
||||
if c == nil || c.rdb == nil {
|
||||
return errors.New("redis client not initialized")
|
||||
}
|
||||
return c.rdb.Publish(ctx, channel, payload).Err()
|
||||
}
|
||||
|
||||
// Subscribe 订阅频道,并在返回前等到 broker 确认订阅生效:
|
||||
// 否则"订阅建立"与"第一条消息到达"之间有一个静默丢消息的窗口。
|
||||
// 返回的 PubSub 由调用方负责 Close。
|
||||
func (c *Client) Subscribe(ctx context.Context, channel string) (*redis.PubSub, error) {
|
||||
if c == nil || c.rdb == nil {
|
||||
return nil, errors.New("redis client not initialized")
|
||||
}
|
||||
ps := c.rdb.Subscribe(ctx, channel)
|
||||
if _, err := ps.Receive(ctx); err != nil {
|
||||
_ = ps.Close()
|
||||
return nil, err
|
||||
}
|
||||
return ps, nil
|
||||
}
|
||||
|
||||
func (c *Client) IncrementWithExpire(ctx context.Context, key string, expire time.Duration) (int64, error) {
|
||||
if c == nil || c.rdb == nil {
|
||||
return 0, nil
|
||||
|
||||
Reference in New Issue
Block a user