RABBITMQ consumer inserts MySQL data and automatically re-connects with disconnection

Source: Internet
Author: User
Connect RABBITMQ Code consumer disconnection: 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 () {//Open 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)//Connect 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")//Create consumer msgs, err: = Ch. Consume (Q.name,//Queue "",//Consumertrue,//Auto-ackfalse,//Exclusivefalse,//No-localfalse,//No-waitnil,//args ) FailOnError (Err, "Failed to register a consumer")//coprocessor gets message queue processing result 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 times  ∙  1 likes  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.