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 贊  
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.