type WatchDog struct {
ctx context.Context
ctxcancel context.CancelFunc
Keys []string
Expiration time.Duration
RedisClient *redis.Client
}
func NewWatchDog(keys []string, expiration time.Duration, redisClient *redis.Client) (*WatchDog) {
ctx, ctxcancel := context.WithCancel(context.Background())
return &WatchDog{
ctx: ctx,
ctxcancel: ctxcancel,
Keys: keys,
Expiration: expiration,
RedisClient: redisClient,
}
}
func (w *WatchDog) Run() {
for {
select {
case <-w.ctx.Done():
return
default:
for _, key := range w.Keys {
exist, err := w.RedisClient.Exists(key).Result()
if err != nil {
logger.Debug("watchdog check exists error", field.Error(err)); continue
} else if exist < 1 {
logger.Debug("watchdog error, key dont exists", field.String("key", key), field.Error(err)); continue
}
w.RedisClient.Expire(key, w.Expiration)
}
time.Sleep(w.Expiration/2)
}
}
}
func (w *WatchDog) Stop() {
w.ctxcancel()
}
go redis 看门狗
于 2024-06-14 11:37:19 首次发布