...
 
Commits (2)
......@@ -17,6 +17,10 @@ func AppIsRelease() bool {
return GetMode() == RELEASE
}
func AppIsLocal() bool {
return GetMode() == LOCAL
}
//数据库的配置
type MysqlConfig struct {
MYSQL_HOST string
......
......@@ -6,14 +6,11 @@ import (
"fmt"
"gorm.io/gorm/schema"
"net"
"net/http"
"net/url"
"os"
"strconv"
"time"
"github.com/go-redis/redis/v8"
consulapi "github.com/hashicorp/consul/api"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
"gorm.io/driver/mysql"
......@@ -502,84 +499,50 @@ func sendKickMessage(c userCenter.RouterClient, msg *userCenter.KickMessage) err
return err
}
func consulCheck(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "consulCheck")
}
const (
RegisterName = "userCenter"
RegisterTag = "用户中心"
)
func registerToConsul(client *consulapi.Client, retry bool) {
checkPort := port + 1000
registration := new(consulapi.AgentServiceRegistration)
hostName, _ := os.Hostname()
registration.ID = fmt.Sprintf("%s-%s", RegisterName, hostName)
registration.Name = RegisterName
registration.Port = port
registration.Tags = []string{RegisterTag}
myIp, myNodeName := "", ""
if localIp, err := common.GetClientIpV2(); err != nil {
mylogrus.MyLog.Fatalln("local ip not found", err)
} else {
myIp = localIp
func RegisterToRedis(RedisClusterClient *redis.Client, port int, init bool) {
// 本地不注册
if appConfig.AppIsLocal() {
return
}
mylogrus.MyLog.Infof("My ip is %s, nodeName: %s\n", myIp, myNodeName)
registration.Address = myIp
registration.Check = &consulapi.AgentServiceCheck{
HTTP: fmt.Sprintf("http://localhost:%d%s", checkPort, "/check"),
Timeout: "3s",
Interval: "5s",
DeregisterCriticalServiceAfter: "30s", //check失败后30秒删除本服务
if RedisClusterClient == nil {
failMsg := fmt.Sprintf("RegisterToRedis fail,redisClusterNotInit,serviceName:%v", RegisterName)
_ = dingding.SendDingRobot(dingding.ROBOTWEBHOOK, failMsg, true)
mylogrus.MyLog.Errorf(failMsg)
return
}
err := client.Agent().ServiceRegister(registration)
redisKey := "service:" + RegisterName
ip, err := common.GetClientIpV2()
if err != nil {
mylogrus.MyLog.Fatal("register server error : ", err)
}
if !retry {
http.HandleFunc("/check", consulCheck)
http.ListenAndServe(fmt.Sprintf(":%d", checkPort), nil)
}
}
// 自愈检查
// 启动后每一分钟检查一次
// 首次启动不执行
func selfCheck() {
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
select {
case <-ticker.C:
client, err := consulapi.NewClient(consulapi.DefaultConfig()) //非默认情况下需要设置实际的参数
if err != nil {
mylogrus.MyLog.Errorf("RegisterToConsul Fail:%v", err)
break
}
if client == nil {
mylogrus.MyLog.Errorf("Fail to get consul client.")
break
}
cataLog := client.Catalog()
if cataLog == nil {
mylogrus.MyLog.Errorf("No catalog.")
break
}
services, _, err := cataLog.Service(RegisterName, "", nil)
if err != nil {
mylogrus.MyLog.Errorf("%v", err)
break
}
if len(services) == 0 {
mylogrus.MyLog.Errorf("%s not found.", RegisterName)
go registerToConsul(client, true) // 重新注册
} else {
mylogrus.MyLog.Infof("%s check success %v", RegisterName, services[0])
failMsg := fmt.Sprintf("RegisterToRedis fail,ip fail,err:%v,serviceName:%v", err, RegisterName)
mylogrus.MyLog.Errorf(failMsg)
_ = dingding.SendDingRobot(dingding.ROBOTWEBHOOK, failMsg, true)
return
}
ipPort := fmt.Sprintf("%s:%d", ip, port)
if err := RedisClusterClient.ZAdd(context.Background(), redisKey, &redis.Z{
Score: float64(time.Now().Unix()),
Member: ipPort,
}).Err(); err != nil {
failMsg := fmt.Sprintf("RegisterToRedis fail,redis fail,err:%v,serviceName:%v", err, RegisterName)
mylogrus.MyLog.Errorf(failMsg)
_ = dingding.SendDingRobot(dingding.ROBOTWEBHOOK, failMsg, true)
}
// 初始化注册自我检查 selfCheck
if init {
go func() {
ticker := time.NewTicker(time.Second * 5)
defer ticker.Stop()
for {
select {
case <-ticker.C:
RegisterToRedis(RedisClusterClient, port, false) // 刷新注册
}
}
}
}()
}
}
......@@ -591,14 +554,13 @@ type HiloConfigs struct {
func main() {
flag.Parse()
config := consulapi.DefaultConfig()
client, err := consulapi.NewClient(config)
if err != nil {
mylogrus.MyLog.Fatal("consul client error : ", err)
}
go registerToConsul(client, false)
go selfCheck()
// init redis cluster
rdbCluster := redis.NewClient(&redis.Options{
Addr: appConfig.GetConfigRedis().REDIS_CLUSTER_HOST,
Password: appConfig.GetConfigRedis().REDIS_CLUSTER_PASSWORD,
})
// 注册到redis
RegisterToRedis(rdbCluster, port, true)
// init redis
rdb := redis.NewClient(&redis.Options{
......