github.com/godaddy-x/freego@v1.0.156/amqp/rabbitmq.go (about) 1 package rabbitmq 2 3 import ( 4 "fmt" 5 "github.com/godaddy-x/freego/utils" 6 "github.com/streadway/amqp" 7 "net" 8 "time" 9 ) 10 11 const ( 12 direct = "direct" 13 ) 14 15 type AmqpConfig struct { 16 DsName string 17 Host string 18 Port int 19 Username string 20 Password string 21 SecretKey string 22 } 23 24 type Option struct { 25 Exchange string `json:"ex"` 26 Queue string `json:"qe"` 27 Kind string `json:"kd"` 28 Router string `json:"ru"` 29 SigTyp int `json:"st"` // 是否加密 0.明文签名 1.AES加密签名 30 SigKey string `json:"-"` // 验签密钥 31 } 32 33 type MsgData struct { 34 Option Option `json:"op"` 35 Durable bool `json:"du"` 36 Content interface{} `json:"co"` 37 Type int64 `json:"ty"` 38 Delay int64 `json:"dy"` 39 Retries int64 `json:"rt"` 40 Nonce string `json:"no"` 41 Signature string `json:"sg"` 42 } 43 44 type DLX struct { 45 DlxExchange string // 死信交换机 46 DlxQueue string // 死信队列 47 DlkExchange string // 重读交换机 48 DlkQueue string // 重读队列 49 DlkCallFunc func(message MsgData) (MsgData, error) // 回调函数 50 } 51 52 // Amqp监听配置参数 53 type Config struct { 54 Option Option 55 Durable bool 56 PrefetchCount int 57 PrefetchSize int 58 IsNack bool 59 AutoAck bool 60 } 61 62 func ConnectRabbitMQ(conf AmqpConfig) (*amqp.Connection, error) { 63 c, err := amqp.DialConfig(fmt.Sprintf("amqp://%s:%s@%s:%d/", conf.Username, conf.Password, conf.Host, conf.Port), amqp.Config{ 64 Dial: func(network, addr string) (net.Conn, error) { 65 return net.DialTimeout(network, addr, 3*time.Second) 66 }, 67 }) 68 if err != nil { 69 return nil, utils.Error("rabbitmq init failed: ", err) 70 } 71 return c, nil 72 }