diff --git a/goctl_template/api/context.tpl b/goctl_template/api/context.tpl index 3195fe63..70f70ff2 100644 --- a/goctl_template/api/context.tpl +++ b/goctl_template/api/context.tpl @@ -18,6 +18,7 @@ type ServiceContext struct { {{.middleware}} MysqlConn *gorm.DB AllModels *gmodel.AllModelsGen + RabbitMq map[string]*initalize.QueueItem } func NewServiceContext(c {{.config}}) *ServiceContext { @@ -26,6 +27,7 @@ func NewServiceContext(c {{.config}}) *ServiceContext { Config: c, MysqlConn: initalize.InitMysql(c.SourceMysql), AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)), + RabbitMq: initalize.InitRabbitMq(c.SourceRabbitMq, nil), {{.middlewareAssignment}} } } diff --git a/initalize/rabbitmq.go b/initalize/rabbitmq.go index 96a4ad1d..484da01f 100644 --- a/initalize/rabbitmq.go +++ b/initalize/rabbitmq.go @@ -5,27 +5,25 @@ import ( "fusenapi/constants" "github.com/streadway/amqp" "log" - "time" ) // handle -type queueItem struct { +type QueueItem struct { Ch *amqp.Channel Queue amqp.Queue } -var mapMq = make(map[string]*queueItem) - -func InitRabbitMq(url string, config *tls.Config) (map[string]*queueItem, error) { +func InitRabbitMq(url string, config *tls.Config) map[string]*QueueItem { conn, err := amqp.DialTLS(url, config) if err != nil { - return nil, err + log.Fatalf("Failed to connect to RabbitMQ: %v", err) } // 创建一个通道 ch, err := conn.Channel() if err != nil { - return nil, err + log.Fatalf("Failed to open a channel: %v", err) } + mapMq := make(map[string]*QueueItem) //声明队列 for _, queueName := range constants.MQ_QUEUE_ARR { q, err := ch.QueueDeclare( @@ -41,27 +39,10 @@ func InitRabbitMq(url string, config *tls.Config) (map[string]*queueItem, error) ch.Close() log.Fatalf("Failed to declare a queue: %v", err) } - mapMq[string(queueName)] = &queueItem{ + mapMq[string(queueName)] = &QueueItem{ Ch: ch, Queue: q, } } - go checkAlive(url, config, conn, ch) - return mapMq, nil -} - -func checkAlive(url string, config *tls.Config, conn *amqp.Connection, ch *amqp.Channel) { - var err error - for { - time.Sleep(time.Second * 1) - //断开重连 - if conn.IsClosed() { - mapMq, err = InitRabbitMq(url, config) - if err == nil { - return - } else { - continue - } - } - } + return mapMq } diff --git a/server/websocket/internal/svc/servicecontext.go b/server/websocket/internal/svc/servicecontext.go index 9a22471e..cecf6811 100644 --- a/server/websocket/internal/svc/servicecontext.go +++ b/server/websocket/internal/svc/servicecontext.go @@ -18,6 +18,7 @@ type ServiceContext struct { MysqlConn *gorm.DB AllModels *gmodel.AllModelsGen + RabbitMq map[string]*initalize.QueueItem } func NewServiceContext(c config.Config) *ServiceContext { @@ -26,6 +27,7 @@ func NewServiceContext(c config.Config) *ServiceContext { Config: c, MysqlConn: initalize.InitMysql(c.SourceMysql), AllModels: gmodel.NewAllModels(initalize.InitMysql(c.SourceMysql)), + RabbitMq: initalize.InitRabbitMq(c.SourceRabbitMq, nil), } }