Golang sending messages using AMQP

Source: Internet
Author: User
Tags rabbitmq
This is a creation in Article, where the information may have evolved or changed.
1.Why use a channel instead of using a TCP connection to send the AMQP command? It is very expensive to establish and destroy the TCP connection frequently for the operating system, while the operating system has an upper limit of connections per second, and the performance bottleneck is unavoidable, but establishing a TCP connection is undoubtedly a good solution, in which a number of channels are established for private communication with RABBITMQ. Equivalent to a fiber optic cable, a cable has multiple beams, the channel is unlimited2.Queue1The AMQP command Basic.consume with Basic.GetYou should use Basic.consumebasic if you want the message to be received automatically as soon as it arrives in the queue.GetSubscribe to a message, get a single message, and unsubscribe, it's worth noting that basic is not recycled.GetInstead of basic.consume, you should rationally use Basic.consume to achieve high throughput messages if you reach an unattended queue, the message waits in the queue, knowing that a consumer subscribes to the queue2Receive a message consumer acknowledgement message tells RABBITMQ that the RABBITMQ will be safe to remove the message from the queue if the consumer receives a message confirming that the RABBITMQ disconnected (or unsubscribed from the queue) before the connection is received. RABBITMQ will assume that the message was not distributed and then distributed to the next subscriber. If your application processes messages time-consuming, you can delay acknowledgement messages to prevent a steady stream of messages from flooding3To reject a message before it is acknowledgedaThe consumer disconnects from the RABBITMQ server and sends the message to the next consumer, but this connection/disconnection method increases the burden on the server B. You can use the Basic.reject command to reject a message with the parametertrue, will be sent to the next consumer,falseThe message will be removed from the queue and will not be distributed to the next consumer4) Queue settings If you want to have a private queue for only one consumer service, you can set the exclusive parameter totrueIf temporary queues are required and combined with exclusive and auto_delete,auto_delete are automatically deleted when the consumer cancels the subscription, they are set totrue3.Three basic exchange types The direct switch is simple: If the routing key matches, the message is posted to the appropriate queue; The FANOUT switch broadcasts the received message to the bound queue; The topic switch enables messages from different sources to reach the same queue.4.The role of Virtual host (Vhost)a. Logical separation allows running data that is secure and confidential for different applications, separating the many customers of rabbit and avoiding naming conflicts between queues and switches ; b. Permission control is Vhost, C.vhost is absolutely isolated, the switch on Vhost1 cannot be bound to a queue in Vhost2, and d. Can safely migrate to new RABBITMQ server to handle new load, there will be no naming conflicts e.vhost not only eliminate the Each tier runs a RABBITMQ server and avoids creating different clusters for each layer5.The persisted policy durable property determines whether RABBITMQ needs to recreate the queue (or exchanger) after a crash or reboot. Three key points: set his delivery mode (delivery mode) option to2(persistent), sent to a persistent switch, and reached the persisted queue. Features: Persistent messages are recovered from the server restart in a persistent log file written to disk, and when a persistent message is published to a persistent exchanger, the message is not responded to after it is submitted to the log file, and the persistent message is automatically removed from the persistence log if it is routed to a non-persisted queue. Unable to recover from server restart; once it is consumed correctly (after confirmation), RABBITMQ marks the message as waiting for garbage collection in the persistence log. Before consumption, if restarted, the server rebuilds the exchanger and queue as well as bindings, replays the messages in the persistence log file to the appropriate queue or switch, depending on which link the message is at the downtime6.Solution to the transaction: Sender acknowledgement mode due to the high performance of AMQP internal transaction, we take the sender acknowledgement mode to guarantee the transaction, set the channel to confirm mode, all the messages posted on this channel will have a unique ID number, when they are posted to the matching queue, The channel sends a sender acknowledgement mode to the producer application, which is asynchronous, and the application can wait for confirmation while continuing to send the next one, but if the message is persisted, the message is sent after the disk is written. If an internal error is sent causing the message to be lost, RABBITMQ sends a nack ( notacknowledged, unconfirmed) messages, which can be traced to millions of messages per minute in this mode7.Performance features7.1Reliability (Reliability) RABBITMQ offers many features that allow us to compromise performance and reliability, including persistence, send acknowledgement, publisher acknowledgement, and high availability.7.2The elastic routing (flexible Routing) message is selected by switching (exchanges) before reaching the queue. RABBITMQ has designed several built-in interchange types for typical routing logic. For more complex routing, we can bind exchanges together or write our own Exchange type plug-in.7.3Clustering (clustering) several RABBITMQ servers within a LAN can be clustered together to form a logical agent.7.4Federation (FEDERATION) for servers that require more loose and unreliable connections than clusters, RABBITMQ provides a federated model (Federation models)7.5The high-availability queue (Hi Available queue) can mirror the queue in several machines in a cluster, ensuring that hardware failures occur immediately and your messages are safe.7.6Multiple protocol (MULTI-PROTOCOL) RABBITMQ support messages are transmitted across multiple protocols.7.7The Multi-client (many clients) RABBITMQ client has any language you can almost imagine.7.8The management interface (Management UI) RABBITMQ comes with an easy-to-use management interface that allows you to monitor and control all aspects of your messaging broker server.7.9Trace (tracing) If your message system behaves abnormally, RABBITMQ provides trace support to identify the root cause of the error.7.10Plug-in systems (Plugin system) RABBITMQ provide plug-in extensions in a variety of ways, and we can implement our own plugins. One advantage of using task queues is that you can easily work with tasks in parallel. When dealing with a large backlog of tasks, simply increase the work queue, in this way, can be easily scaled.
Send code: PackageMainImport("Log"    "GITHUB.COM/STREADWAY/AMQP")funcFailOnError (err Error, MSGstring) {ifErr! =Nil{log. Fatalf ('%s:%s ', MSG, err)}}funcMain () {conn, err: = Amqp. Dial ("amqp://root:123456@localhost:5672/") FailOnError (Err,"Failed to connect to RabbitMQ")deferConn. Close () ch, err: = conn. Channel () FailOnError (err,"Failed to open a channel")deferCh. Close () Err = ch. Publish ("Test",//Exchange        "Agent",//Routing key        false,//Mandatory        false,//ImmediateAmqp. publishing{ContentType:"Text/plain", MessageId:string(1), Type:"Agentjob", Body: []byte("Hello World"),}) log. Println ("Send OK") FailOnError (Err,"Failed to publish a message")}
Receive code: PackageMainImport("Log"    "GITHUB.COM/STREADWAY/AMQP")funcFailOnError (err Error, MSGstring) {ifErr! =Nil{log. Fatalf ('%s:%s ', MSG, err)}}funcMain () {conn, err: = Amqp. Dial ("amqp://root:123456@localhost:5672/") FailOnError (Err,"Failed to connect to RabbitMQ")deferConn. Close () ch, err: = conn. Channel () FailOnError (err,"Failed to open a channel") Ch. Reject () Q, err: = Ch. Queuedeclare ("Agent",//Name        true,//Durable        true,//delete when usused        false,//Exclusive        false,//No-wait        Nil,//Arguments) FailOnError (Err,"Failed to declare a queue") msgs, err: = Ch. Consume (Q.name,//Queue        "",//Consumer        true,//Auto-ack        false,//Exclusive        false,//No-local        false,//No-wait        Nil,//args) FailOnError (Err,"Failed to register a consumer") Err = Ch. Queuebind ("Agent","Agent","Test_01",false,Nil)ifErr! =Nil{log. PRINTLN (ERR)return} Forever: = Make(Chan BOOL)Go func() { forD: =Rangemsgs {log. PRINTLN (d.type) log. PRINTLN (D.messageid) log. Printf ("Received a message:%s", D.body)}} () log. Printf ("Waiting for messages." To exit Press CTRL + C ") <-forever}
Related Article

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.