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/jobs_gorm_redis_get.go

97 lines
2.3 KiB

2 years ago
package gojobs
import (
"context"
"errors"
"fmt"
"go.dtapp.net/gojobs/jobs_gorm_model"
"go.dtapp.net/gostring"
2 years ago
"log"
2 years ago
"math/rand"
"time"
)
// GetIssueAddress 获取下发地址
// workers 在线列表
// v 任务信息
// ---
// address 下发地址
// err 错误信息
func (j *JobsGorm) GetIssueAddress(workers []string, v *jobs_gorm_model.Task) (address string, err error) {
2 years ago
var (
currentIp = "" // 当前Ip
appointIpStatus = false // 指定Ip状态
)
// 赋值ip
if v.SpecifyIp != "" {
currentIp = v.SpecifyIp
appointIpStatus = true
}
// 只有一个客户端在线
if len(workers) == 1 {
2 years ago
if appointIpStatus == true {
// 判断是否指定某ip执行
if gostring.Contains(workers[0], currentIp) == true {
2 years ago
return j.config.cornKeyPrefix + "_" + v.SpecifyIp, nil
2 years ago
}
return address, errors.New(fmt.Sprintf("需要执行的[%s]客户端不在线", currentIp))
2 years ago
}
2 years ago
return j.config.cornKeyPrefix + "_" + workers[0], nil
2 years ago
}
// 优先处理指定某ip执行
if appointIpStatus == true {
for wk, wv := range workers {
if gostring.Contains(wv, currentIp) == true {
2 years ago
return j.config.cornKeyPrefix + "_" + workers[wk], nil
2 years ago
}
}
return address, errors.New(fmt.Sprintf("需要执行的[%s]客户端不在线", currentIp))
2 years ago
} else {
// 随机返回一个
zxIp := workers[j.random(0, len(workers))]
2 years ago
if zxIp == "" {
return address, errors.New("获取执行的客户端异常")
}
2 years ago
address = j.config.cornKeyPrefix + "_" + zxIp
2 years ago
return address, err
}
}
// GetSubscribeClientList 获取在线的客户端
func (j *JobsGorm) GetSubscribeClientList(ctx context.Context) ([]string, error) {
2 years ago
if j.config.debug == true {
2 years ago
log.Printf("获取在线的客户端:%s\n", j.config.cornKeyPrefix+"_*")
2 years ago
}
// 扫描
2 years ago
values, err := j.redisClient.Keys(ctx, j.config.cornKeyPrefix+"_*").Result()
2 years ago
if err != nil {
if err == errors.New("ERR wrong number of arguments for 'mget' command") {
return []string{}, nil
}
return nil, errors.New(fmt.Sprintf("获取失败:%s", err.Error()))
2 years ago
}
client := make([]string, 0, len(values))
2 years ago
for _, val := range values {
client = append(client, val.(string))
2 years ago
}
return client, nil
2 years ago
}
// 随机返回一个
// min最小
// max最大
2 years ago
func (j *JobsGorm) random(min, max int) int {
if max-min <= 0 {
return 0
}
rand.Seed(time.Now().Unix())
return rand.Intn(max-min) + min
}