60 lines
1.4 KiB
Go
60 lines
1.4 KiB
Go
package rabbitmq
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
"os"
|
||
"sync"
|
||
|
||
"github.com/gogf/gf/v2/frame/g"
|
||
"github.com/gogf/gf/v2/util/guid"
|
||
)
|
||
|
||
var (
|
||
instanceId string
|
||
instanceOnce sync.Once
|
||
)
|
||
|
||
// getInstanceId 获取当前实例的唯一标识(单例)
|
||
// 优先级:配置文件 > 环境变量 > 容器名/主机名 > 随机UUID
|
||
func getInstanceId() string {
|
||
instanceOnce.Do(func() {
|
||
ctx := context.Background()
|
||
|
||
// 1. 优先从配置文件读取(手动指定,最高优先级)
|
||
instanceId = g.Cfg().MustGet(ctx, "rabbitmq.instanceName").String()
|
||
if instanceId != "" {
|
||
return
|
||
}
|
||
|
||
// 2. 读取环境变量(Docker/K8s部署时设置)
|
||
instanceId = os.Getenv("INSTANCE_NAME")
|
||
if instanceId != "" {
|
||
return
|
||
}
|
||
|
||
// 3. 使用主机名(Docker容器名/主机名)
|
||
hostname, err := os.Hostname()
|
||
if err != nil || hostname == "" {
|
||
hostname = "unknown"
|
||
}
|
||
|
||
// 4. 如果主机名是默认值(本地开发),添加随机后缀避免冲突
|
||
if hostname == "localhost" || hostname == "unknown" {
|
||
instanceId = hostname + "." + guid.S()[:4]
|
||
} else {
|
||
instanceId = hostname
|
||
}
|
||
})
|
||
return instanceId
|
||
}
|
||
|
||
// GetInstanceQueueName 获取当前实例的响应队列名
|
||
// 格式:{baseQueue}.{hostname}.{uuid8}
|
||
func GetInstanceQueueName(baseQueue string) string {
|
||
if baseQueue == "" {
|
||
baseQueue = "ragflow.response"
|
||
}
|
||
return fmt.Sprintf("%s.%s", baseQueue, getInstanceId())
|
||
}
|