Messaging middleware --RabbitMQ (five) Quick Start producers and consumers, SpringBoot integrate RabbitMQ!

Seeking attention

Quick Start producers and consumers, SpringBoot integrate RabbitMQ!

Foreword

In this chapter we come to a quick start RabbitMQ-- producers and consumers. We need to build a model of the production side and consumption side. What does that mean? Our producer sends a message that is delivered to the RabbitMQ cluster Broker. Our consumer side listens RabbitMQ, when there are messages in the queue and found it to consume.

1. Preparing the Environment

This integration mainly SpringBoot framework, need to have some understanding of the use of SpringBoot.

2. Probably steps

We probably look at the steps of:

  • ConnectionFacorty: the connection factory
  • Connection: a connection
  • Channel: data communication channel can send and receive messages
  • Queue: Queue specific message storage
  • Producer & Consumer producers and consumers

This connection factory need to configure the appropriate information, such as: RabbitMQ node address, port number, etc. VirtualHost. Channel is the key to our RabbitMQ message all interact.

3. project combat

3.1 Connection Factory


/**
 * 
* @ClassName: ConnectionUtils 
* @Description: 连接工具类
* @author Coder编程
* @date 2019年6月21日 上午22:28:22 
*
 */
public class ConnectionUtils {
    public static Connection getConnection() throws IOException, TimeoutException {
        //定义连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置服务地址
        factory.setHost("127.0.0.1");
        //端口
        factory.setPort(5672);//amqp协议 端口 类似与mysql的3306
        //设置账号信息,用户名、密码、vhost
        factory.setVirtualHost("/vhost_cp");
        factory.setUsername("user_cp");
        factory.setPassword("123456");
        // 通过工程获取连接
        Connection connection = factory.newConnection();
        return connection;
    }
}

复制代码

3.2 Production end


/**
 * 
* @ClassName: Producer 
* @Description: 生产者
* @author Coder编程
* @date 2019年7月30日 上午21:04:43 
*
 */
public class Producer {

	
	public static void main(String[] args) throws Exception {
	
		System.out.println("Producer start...");
		
		//1 创建ConnectionFactory
		Connection connection = ConnectionUtils.getConnection();
		
		//2 通过connection创建一个Channel
		Channel channel = connection.createChannel();
		
		//3 通过Channel发送数据
		for(int i=0; i < 5; i++){
			String msg = "Hello RabbitMQ!";
			//1 exchange   2 routingKey 
			channel.basicPublish("", "test001", null, msg.getBytes());
		}

		//4 记得要关闭相关的连接
		channel.close();
		connection.close();
	}
}



复制代码

3.3 Consumer end


/**
 * 
* @ClassName: Consumer 
* @Description: 消费端
* @author Coder编程
* @date 2019年7月30日 上午21:08:12 
*
 */
public class Consumer {

	public static void main(String[] args) throws Exception {
		
		System.out.println("Consumer start...");
		
		//1 创建ConnectionFactory
		Connection connection = ConnectionUtils.getConnection();
		
		//2通过connection创建一个Channel
		Channel channel = connection.createChannel();
		
		//3声明(创建)一个队列
		String queueName = "test001";
		channel.queueDeclare(queueName, true, false, false, null);
		
		//4创建消费者
		QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
		
		//5设置Channel
		channel.basicConsume(queueName, true, queueingConsumer);
		
		while(true){
			//6 获取消息
			Delivery delivery = queueingConsumer.nextDelivery();
			String msg = new String(delivery.getBody());
			System.err.println("消费端: " + msg);
			//Envelope envelope = delivery.getEnvelope();
		}
		
	}
}




复制代码

3.4 source code parsing


channel.queueDeclare(queueName, true, false, false, null);

复制代码

Underlying code

The first argument: queuename: name of the queue of the second argument: durable if persistent. After the true message is persisted to local, restart the service to ensure that messages are not lost third argument: exclusive: Exclusive representation, is set to true necessary in certain situations, such as: the order of consumption. There is only one channel can go to listen, no other channel can listen. The purpose is to ensure that the order of the consumer. The fourth parameter: autoDelete: queue if the Exchange is not binding, it is automatically deleted fifth parameter: arguments: Extended Parameters


channel.basicConsume(QUEUE_NAME, true, consumer);

复制代码

The second parameter autoAck: automatically sign message

3.5 to run the program

(1) Start the consumer side

Start consumer side

(2) See table control

Overview
You can see that there is a connection, a channel, and other information of a consumer.

Connections
Channels
You can see the current status of the channel is the idle state.

queues
More test001 queue queue.

About this control desk can look at this article:

(3) Production run end

Running the production side
Consumer end message is received
It can be seen stopped production after the end after sending the message, the consumer end quickly receive the message. You can continue to control the situation stations observed by the consumer.

(4) issues

note:

There may be a question: why did you start spending it end?

In the end the consumer because the queue is created, we must have a queue to be able to send a message.

Another problem: In the production side code:


channel.basicPublish("", "test001", null, msg.getBytes());

复制代码

It does not set exchange, set only the name of the queue, the consumer side but still be able to consume the message, which is why?

A: The message must be specified Exchange, or if you do not specify Exchange Exchange is empty, it will default to go first

Default Exchange
Its routing rules: the same-named queues Queue message routing in the past, if the route is not in the past, will be to delete the message.

The end of the sentence

Welcome attention to personal micro-channel public number: Coder program for the latest original technical articles and free learning materials, a lot more boutique mind maps, interview data, PMP preparation materials waiting for you to lead, allowing you to learn technical knowledge anytime, anywhere! Create a qq group: 315 211 365, we welcome into the group exchange study together. Thank you! Can also be introduced to the side of a friend in need.

Articles included to Github: github.com/CoderMerlin... Gitee: gitee.com/573059382/c... welcome attention and star ~

Micro-channel public number

Reference article:

www.cnblogs.com/myJavaEE/p/…

"RabbitMQ messaging middleware succinctly"

recommended article:

Messaging middleware --RabbitMQ (two) major mainstream messaging middleware comprehensive comparison introduced!

Messaging middleware --RabbitMQ (c) understand the core concepts and RabbitMQ AMQP protocol!

Message middleware --RabbitMQ (four) basic operation of the command line and control station!

Guess you like

Origin juejin.im/post/5d441f81518825246a151c2c