使用redis

时间:2018-01-21 16:34:09

标签: go redis cron synchronization

我有四个独立的服务器运行实例,我希望其中只有一个每5秒运行一次查询。我遇到的问题是,他们似乎能够检查我最后一次运行查询时设置的redis密钥,以便多个实例同时运行我的查询。

我使用包cron for go:

c.AddFunc(config.CronInterval, func() {
    KeyExpired(redisClient, cronInterval)
})
c.Start()

这是我的KeyExpired func

var CronInterval = "@every 5s"
func KeyExpired(redisClient *redis.Client, cronInterval time.Duration) bool {
    //Convert the duration in the config to seconds
    cronIntervalSeconds := int64(cronInterval.Seconds())
    //Get the last value that was set as reporting time
    rval := redisClient.Get("StatReporting")
    if rval.Err() != nil {
        redisClient.Set("StatReporting", time.Now().UTC().Format(timeFormat), 0)
        return false
    }
    lastRun, err := time.Parse(timeFormat, rval.Val())
    if err != nil {
        log.Error(err.Error())
        redisClient.Set("StatReporting", time.Now().UTC().Format(timeFormat), 0)
        return false
    }

    if (time.Now().UTC().Unix() - lastRun.UTC().Unix()) >= cronIntervalSeconds {
        fmt.Println(config.Port, time.Now().UTC().Unix())
        redisClient.Set("StatReporting", time.Now().Add(time.Second).UTC().Format(timeFormat), 0)
        return true
    } else {
        fmt.Println(config.Port, "WAITING")
        return false
    }
}

以下是运行4个实例的输出:

5559 1516551859
5558 1516551859
5777 WAITING
9999 WAITING
5559 WAITING
5558 WAITING
5777 1516551865
9999 WAITING
5559 WAITING
5558 WAITING
5777 WAITING
9999 1516551872
5559 WAITING
5558 WAITING
5777 WAITING
9999 WAITING
5558 1516551879
5559 1516551879
5777 WAITING
9999 WAITING
5559 WAITING
5558 WAITING
5777 1516551885
9999 WAITING
5558 WAITING
5559 WAITING
5777 WAITING

0 个答案:

没有答案