Rabbitmq a note

Some basic concepts

 Producer 

Manufacturer, send one message, client left side in FIG.

Consumer

consumer client, one of the received message, in the rear side of FIG.

Broker

Messaging middleware service node, usually a RabbitMQ Broker as a RabbitMQ server.

News

Message contains two parts: message body and tag. Message body (payload) having a logical structure business data, such as a JSON string. Tag message used to describe this message, such as a name and a switch routing keys. The news producers referred RabbitMQ, will send a message to interested consumers under the label after RabbitMQ.

connection

In fact, the connection is a TCP connection, if producers or consumers need to establish a connection and Broker.

Nobumichi

Channel Connection is based on the virtual connection, each instruction RabbitMQ AMQP process is accomplished by channel.

Why introduction channel it? Imagine a scenario where an application has many threads need to consume messages from RabbitMQ, or in the production of news, then the inevitable need to establish a number of Connection, which is a lot of TCP connections. However, to the operating system, TCP connection is created and destroyed very expensive overhead, if they use a peak performance bottlenecks also will appear. RabbitMQ similar NIO '(Non-blocking 1/0) this selected TCP connection multiplexing, not only can reduce the performance overhead, but also easy to manage.

queue

RabbitMQ internal object queue is for storing a message, when a plurality of consumers can subscribe to the same queue, then the message queue is shared equally (Round-Robin, i.e. polling) for processing to a plurality of consumers, and not every consumer will receive all the news well treatment.

switch

Producer will send messages to the Exchange (switches, may be usually represented by a capital "X"), the switch routes the message to one or more queues. If the route is less than might be returned to the producer, and perhaps discarded.

 

Routing keys

When the producers message to the switch, usually assigns a RoutingKey, it is used to specify the message routing rules, and this RoutingKey need to exchange types and key bindings (BindingKey) used in combination in order to ultimately take effect.

 Binding

RabbitMQ bound by the exchanger associated with the queue, will typically specify a binding key (bindingKey) when bound, so RabbitMQ know how to route messages to the correct queue.

Producer sends a message to the switch, a need RoutingKey, and when BindingKey RoutingKey match, the message is routed to a corresponding queue. Bound to the same in a plurality of queues of the switch, these bindings allows the same BindingKey. BindingKey not take effect in all cases, it depends on the type of switch, such as switch type fanout will ignore bindingKey, but the message is routed to switch all bound to the queue.

Switch type

RabbitMQ common types exchanger fanout, direct, topic, headers four. 

fanout 

It would all be sent to the switch to route all messages bound with the switch queue corresponding to the broadcast mode.

direct

Routes the message to those BindingKey and RoutingKey exact match queue.

topic

And routing messages to BindingKey RoutingKey match queue.

headers 

headers exchanger type matching rule does not depend on routing keys to route the message, but according to the match in the content transmission message headers property.

 Producers and consumers of the transfer process

Producers transfer process

 

Consumer transfer process

 

Sample Code

package com.spring.hello.demo.mq;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

public class RabbitProducer {
	private static final String EXCHANGE_NAME = "exchange_demo";
	private static final String ROUTING_KEY = " routingkey_demo";
	private static final String QUEUE_NAME = "queue_demo";
	private static final String IP_ADDRESS = "192.168.93.131";
	private static final int PORT = 5672;// RabbitMQ

	public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost(IP_ADDRESS);
		factory.setPort(PORT);
		factory.setUsername("guest");
		factory.setPassword("guest");
		Connection connection = factory.newConnection (); // create a connection
		Channel channel = connection.createChannel();
		// // Create a channel to create a type = "direct", persistent, non-automatic deletion switch
		channel.exchangeDeclare(EXCHANGE_NAME, "direct", true, false, null); 
		// create a persistent, non-exclusive, non-automatic deletion queue
		channel.queueDeclare(QUEUE_NAME, true, false, false, null); 
		// switch to the queue via the routing key binding
		channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY); 
		// send a persistent message: Hello World!
		String message = "Hello World!";
		channel.basicPublish(EXCHANGE_NAME, ROUTING_KEY, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
		// Close the resource
		channel.close();
		connection.close();
	}
}


package com.spring.hello.demo.mq;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Address;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class RabbitConsumer {
	private static final String QUEUE_NAME = "queue_demo";
	private static final String IP_ADDRESS = "192.168.93.131";
	private static final int PORT = 5672;// RabbitMQ

	public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
		Address[] addresses = new Address[] { new Address(IP_ADDRESS, PORT) };
		ConnectionFactory factory = new ConnectionFactory();
		factory.setUsername("guest");
		factory.setPassword("guest");
		// connection here with the demo producers slightly different, pay attention to distinguish the difference
		Connection connection = factory.newConnection(addresses); // 创建连接
		final Channel channel = connection.createChannel (); // Create Channel
		channel.basicQos (64); ack message has not been received // set the maximum number of clients
		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
					throws IOException {
				System.out.println("recv message: " + new String(body));
				try {
					TimeUnit.SECONDS.sleep(1);
				} catch (InterruptedException e) {
					e.printStackTrace ();
				}
				//channel.basicAck(envelope.getDeliveryTag(), false);
			}
		};
		channel.basicConsume (QUEUE_NAME, consumer); // wait after the callback function is finished, close the resource
		TimeUnit.SECONDS.sleep(15);
		channel.close();
		connection.close();

	}
}

  

 

Guess you like

Origin www.cnblogs.com/lostyears/p/10927131.html