Commit b7ad676a authored by iamhujiebin's avatar iamhujiebin

feat:注册到redis

parent d144feff
...@@ -6,14 +6,11 @@ import ( ...@@ -6,14 +6,11 @@ import (
"fmt" "fmt"
"gorm.io/gorm/schema" "gorm.io/gorm/schema"
"net" "net"
"net/http"
"net/url" "net/url"
"os"
"strconv" "strconv"
"time" "time"
"github.com/go-redis/redis/v8" "github.com/go-redis/redis/v8"
consulapi "github.com/hashicorp/consul/api"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/keepalive" "google.golang.org/grpc/keepalive"
"gorm.io/driver/mysql" "gorm.io/driver/mysql"
...@@ -502,84 +499,46 @@ func sendKickMessage(c userCenter.RouterClient, msg *userCenter.KickMessage) err ...@@ -502,84 +499,46 @@ func sendKickMessage(c userCenter.RouterClient, msg *userCenter.KickMessage) err
return err return err
} }
func consulCheck(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "consulCheck")
}
const ( const (
RegisterName = "userCenter" RegisterName = "userCenter"
RegisterTag = "用户中心"
) )
func registerToConsul(client *consulapi.Client, retry bool) { func RegisterToRedis(RedisClusterClient *redis.Client, port int, init bool) {
checkPort := port + 1000 if RedisClusterClient == nil {
registration := new(consulapi.AgentServiceRegistration) failMsg := fmt.Sprintf("RegisterToRedis fail,redisClusterNotInit,serviceName:%v", RegisterName)
hostName, _ := os.Hostname() _ = dingding.SendDingRobot(dingding.ROBOTWEBHOOK, failMsg, true)
registration.ID = fmt.Sprintf("%s-%s", RegisterName, hostName) mylogrus.MyLog.Errorf(failMsg)
registration.Name = RegisterName return
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
}
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秒删除本服务
} }
err := client.Agent().ServiceRegister(registration) redisKey := "service:" + RegisterName
ip, err := common.GetClientIpV2()
if err != nil { if err != nil {
mylogrus.MyLog.Fatal("register server error : ", err) failMsg := fmt.Sprintf("RegisterToRedis fail,ip fail,err:%v,serviceName:%v", err, RegisterName)
} mylogrus.MyLog.Errorf(failMsg)
if !retry { _ = dingding.SendDingRobot(dingding.ROBOTWEBHOOK, failMsg, true)
http.HandleFunc("/check", consulCheck) return
http.ListenAndServe(fmt.Sprintf(":%d", checkPort), nil) }
} ipPort := fmt.Sprintf("%s:%d", ip, port)
} if err := RedisClusterClient.ZAdd(context.Background(), redisKey, &redis.Z{
Score: float64(time.Now().Unix()),
// 自愈检查 Member: ipPort,
// 启动后每一分钟检查一次 }); err != nil {
// 首次启动不执行 failMsg := fmt.Sprintf("RegisterToRedis fail,redis fail,err:%v,serviceName:%v", err, RegisterName)
func selfCheck() { mylogrus.MyLog.Errorf(failMsg)
ticker := time.NewTicker(time.Minute) _ = dingding.SendDingRobot(dingding.ROBOTWEBHOOK, failMsg, true)
}
// 初始化注册自我检查 selfCheck
if init {
go func() {
ticker := time.NewTicker(time.Second * 5)
defer ticker.Stop() defer ticker.Stop()
for { for {
select { select {
case <-ticker.C: case <-ticker.C:
client, err := consulapi.NewClient(consulapi.DefaultConfig()) //非默认情况下需要设置实际的参数 RegisterToRedis(RedisClusterClient, port, false) // 刷新注册
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])
} }
} }
}()
} }
} }
...@@ -591,14 +550,13 @@ type HiloConfigs struct { ...@@ -591,14 +550,13 @@ type HiloConfigs struct {
func main() { func main() {
flag.Parse() flag.Parse()
config := consulapi.DefaultConfig() // init redis cluster
rdbCluster := redis.NewClient(&redis.Options{
client, err := consulapi.NewClient(config) Addr: appConfig.GetConfigRedis().REDIS_CLUSTER_HOST,
if err != nil { Password: appConfig.GetConfigRedis().REDIS_CLUSTER_PASSWORD,
mylogrus.MyLog.Fatal("consul client error : ", err) })
} // 注册到redis
go registerToConsul(client, false) RegisterToRedis(rdbCluster, port, true)
go selfCheck()
// init redis // init redis
rdb := redis.NewClient(&redis.Options{ rdb := redis.NewClient(&redis.Options{
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment