rabbitmq消費者插入mysql資料並實現斷線自動重連
來源:互聯網
上載者:User
串連rabbitmq的代碼消費者斷線重連:package mainimport ("log""github.com/streadway/amqp""database/sql"_"github.com/go-sql-driver/mysql"//"time")func insert(db *sql.DB, a []byte) {stmt, err := db.Prepare("INSERT INTO rabbit (name) VALUES(?)")stmt.Exec(a)defer stmt.Close()if err != nil {log.Println(err)return}}func failOnError(err error, msg string) {if err != nil {log.Fatalf("%s: %s", msg, err)}}func main() {//開啟mysqldb, err := sql.Open("mysql", "root:0022....hh@tcp(127.0.0.1:3306)/rabbitmq?charset=utf8")if err != nil {log.Fatalf("Open database error: %s\n", err)}defer db.Close()err = db.Ping()if err != nil {log.Fatal(err)}//forever := make(chan bool)//串連rabbitmqfor {conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")if err != nil {continue}failOnError(err, "Failed to connect to RabbitMQ")defer conn.Close()ch, err := conn.Channel()failOnError(err, "Failed to open a channel")defer ch.Close()q, err := ch.QueueDeclare("hello", // nametrue, // durablefalse, // delete when unusedfalse, // exclusivefalse, // no-waitnil, // arguments)failOnError(err, "Failed to declare a queue")// 建立消費者msgs, err := ch.Consume(q.Name, // queue"", // consumertrue, // auto-ackfalse, // exclusivefalse, // no-localfalse, // no-waitnil, // args)failOnError(err, "Failed to register a consumer")// 協程擷取訊息佇列處理結果go func() {for d := range msgs {log.Printf("Received a message: %s", d.Body)insert(db, d.Body)}}()if conn != nil {//time.Sleep(50*time.Second)continue}log.Printf(" [*] Waiting for messages. To exit press CTRL+C")//<-forever}}115 次點擊 ∙ 1 贊