You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
gojobs/redis_get.go

91 lines
2.3 KiB

2 years ago
package gojobs
import (
"context"
"errors"
"fmt"
2 years ago
"go.dtapp.net/goip"
2 years ago
"go.dtapp.net/gojobs/jobs_gorm_model"
"go.dtapp.net/gostring"
2 years ago
"math/rand"
"time"
)
// GetIssueAddress 获取下发地址
// workers 在线列表
// v 任务信息
// ---
// address 下发地址
// err 错误信息
2 years ago
func (c *Client) GetIssueAddress(ctx context.Context, workers []string, v *jobs_gorm_model.Task) (string, error) {
2 years ago
var (
currentIp = "" // 当前Ip
appointIpStatus = false // 指定Ip状态
)
2 years ago
if v.SpecifyIp != "" {
v.SpecifyIp = goip.IsIp(v.SpecifyIp)
}
2 years ago
// 赋值ip
2 years ago
if v.SpecifyIp != "" && v.SpecifyIp != SpecifyIpNull {
2 years ago
currentIp = v.SpecifyIp
appointIpStatus = true
}
// 只有一个客户端在线
if len(workers) == 1 {
2 years ago
if appointIpStatus {
2 years ago
// 判断是否指定某ip执行
2 years ago
if gostring.Contains(workers[0], currentIp) {
2 years ago
c.zapLog.WithTraceId(ctx).Sugar().Info("只有一个客户端在线指定某ip执行", workers[0], currentIp)
2 years ago
return workers[0], nil
2 years ago
}
2 years ago
return "", errors.New(fmt.Sprintf("需要执行的[%s]客户端不在线", currentIp))
2 years ago
}
2 years ago
return workers[0], nil
2 years ago
}
// 优先处理指定某ip执行
2 years ago
if appointIpStatus {
for wk, wv := range workers {
2 years ago
if gostring.Contains(wv, currentIp) {
2 years ago
c.zapLog.WithTraceId(ctx).Sugar().Info("优先处理指定某ip执行", workers[wk], currentIp)
2 years ago
return workers[wk], nil
2 years ago
}
}
2 years ago
return "", errors.New(fmt.Sprintf("需要执行的[%s]客户端不在线", currentIp))
2 years ago
} else {
// 随机返回一个
2 years ago
address := workers[c.random(0, len(workers))]
2 years ago
if address == "" {
2 years ago
return address, errors.New("获取执行的客户端异常")
}
2 years ago
c.zapLog.WithTraceId(ctx).Sugar().Info("随机返回一个:", address, currentIp)
2 years ago
return address, nil
2 years ago
}
}
// GetSubscribeClientList 获取在线的客户端
2 years ago
func (c *Client) GetSubscribeClientList(ctx context.Context) (client []string, err error) {
2 years ago
// 查询活跃的channel
2 years ago
client, err = c.cache.redisClient.PubSubChannels(ctx, c.cache.cornKeyPrefix+"_*").Result()
2 years ago
if err != nil {
2 years ago
c.zapLog.WithTraceId(ctx).Sugar().Errorf("获取在线的客户端失败:%s%v", c.cache.cornKeyPrefix+"_*", err)
2 years ago
}
2 years ago
return client, err
2 years ago
}
// 随机返回一个
// min最小
// max最大
2 years ago
func (c *Client) random(min, max int) int {
2 years ago
if max-min <= 0 {
return 0
}
rand.Seed(time.Now().Unix())
return rand.Intn(max-min) + min
}