rabbitMQ installation and use in java environment (2)

After installing rabbitMQ, the following is the use of rabbitMQ in the JAVA environment

The blogger has searched the Internet for a long time and has not found a book about rabbitMQ written in the java environment. There is a book "RabbitMQ Practical Combat ++ Efficient Deployment of Distributed Message Queues" which is also written in python as the language environment. It should be this name, Bloggers will not upload attachments, please search by yourself

code directly

package com.lzdn;
/**
 * Initial abstract class
 */
import java.io.IOException;

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

public abstract class EndPoint {
	protected Channel channel;
	protected Connection connection;
	protected String endPontName;
	
	
	public EndPoint(String endpointName) throws IOException{
		this.endPontName = endpointName;
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("192.168.16.201");
		//The default port is selected by default for the insertion port
		//factory.setPort(port);
		factory.setUsername("admin");
		factory.setPassword("admin");
		connection=factory.newConnection();
		channel=connection.createChannel();
		/**
		 * declare an exchange
		 */
		//channel.exchangeDeclare("this", "topic", true, false, null);
		/**
		 * declare a queue
		 * channel.queueDeclare(queue, durable, exclusive, autoDelete, arguments);
		 * @param queue the name of the queue
	     * @param durable set to true if we declare a durable queue (the queue will survive server restarts)
	     * @param exclusive exclusive is set to true if we declare an exclusive queue (only for this connection)
	     * @param autoDelete set to true if we declare an auto delete queue (the server will delete it when it is no longer used)
	     * @param arguments Other properties of the queue (construction parameters).
		*/
		channel.queueDeclare(endpointName, false, false, false, null);
		/**
		 * Bind the exchange to the queue
		 */
		//channel.queueBind(queue, exchange, routingKey)
	}
	public void close() throws IOException{
		this.channel.close();
		this.connection.close();
	}

}
package com.lzdn;

import java.io.IOException;
import java.io.Serializable;

import org.apache.commons.lang.SerializationUtils;

/**
 * Producer
 * @author chuan
 *
 */
public class Producer extends EndPoint{

	public Producer(String endpointName) throws IOException {
		super(endpointName);
	}
	public void sendMessage(Serializable object)throws IOException{
		/**
		 * Parameters:
		 * exchange: the exchange to publish the message/
		 * toroutingKey: the routing key
		 * (default exchange: if an exchange is declared with an empty string, the system will use the exchange "amq.direct",
		 * When we create a queue, by default there will be a routingKey with the same name as the new queue bound to this default exchange)
		 * props: other properties for the message - routing headers etc
		 * body: the message body
		 * channel.basicPublish(exchange, routingKey, props, body);
		 */
		channel.basicPublish("", endPontName, null, SerializationUtils.serialize(object));
	}
	
}
package com.lzdn;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.lang.SerializationUtils;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ShutdownSignalException;

public class QueueConsumer extends EndPoint implements Runnable,Consumer{

	public QueueConsumer(String endpointName) throws IOException {
		super(endpointName);
	}

	public void handleCancel(String arg0) throws IOException {
	}

	public void handleCancelOk(String arg0) {
	}
	/**
	 * Called when consumer is registered.
	 * Called when the user registers.
	 */
	public void handleConsumeOk(String consumerTag) {
        System.out.println("Consumer " + consumerTag + " registered");
	}
	/**
	 *  Called when new message is available.
	 * Called when a new message is available.
	 */
	public void handleDelivery(String consumerTag, Envelope env, BasicProperties props, byte[] body) throws IOException {
		Map map = (Map) SerializationUtils.deserialize(body);
		System.out.println(Thread.currentThread().getStackTrace()[1].getFileName()+"Message Number " + map.get("message number") + " received.");
		/**
		 * When channel.basicConsume(endPontName, false, this); is set to false, you need to open the message reply
		 */
		channel.basicAck(env.getDeliveryTag(), false);
	}

	public void handleRecoverOk(String arg0) {
	}

	public void handleShutdownSignal(String arg0, ShutdownSignalException arg1) {
	}

	public void run() {
		try {
			/**
			 *  @param autoAck true if the server should consider messages
			 * acknowledged once delivered; false if the server should expect
			 * Set the basicConsume method parameter to false, open the message reply
			 */
			channel.basicConsume(endPontName, false, this);
		}catch (Exception e) {
			e.printStackTrace ();
		}
	}

}
package com.lzdn;

import java.io.IOException;
import java.util.HashMap;


public class Main {
	public Main() throws IOException {
		// start the consumer
		QueueConsumer consumer = new QueueConsumer("queue");
		Thread consumerThread = new Thread(consumer);
		consumerThread.start();
		//test2. Start the second consumer into polling mode
		QueueConsumer2 consumer2 = new QueueConsumer2("queue");
		Thread consumerThread2 = new Thread(consumer2);
		consumerThread2.start();
		
		//
		Producer producer = new Producer("queue");
		for (int i = 0; i < 20; i++) {
			HashMap message = new HashMap();
			message.put("message number", i);
			producer.sendMessage(message);
			System.out.println("Message Number " + i + " sent.");
		}
		
	}
	public static void main(String[] args) throws IOException {
		Main ssd = new Main();
	}
}

When not setting the exchange (exchange), rabbitmq defaults to the Direct exchange mode, which is a direct connection to the switch. This mode is to send data to the specified queue according to the routingKey (here to distinguish the 4 stages of rabbitmq data <personal understanding>: transmission entry stage, switch stage, queue stage, consumer consumption stage),

Creating an exchange in the java environment is

channel.exchangeDeclare("this", "topic", true, false, null);//This method creates an exchange that is an exchange

The first parameter of this method is the name of the specified exchange, the second parameter is the type of the exchange (that is, the 4 major exchanges), and the third parameter is whether the exchange is persistent (true persistence, false not persistent) change) The fourth parameter is whether the exchange is automatically deleted after the exchange is not used (true is automatically deleted, false is not deleted), and the fifth parameter is other construction parameters

channel.queueDeclare(endpointName, false, false, false, null);//This method creates a queue and the parameters are explained in the above code

channel.queueBind(queue, exchange, routingKey);//This method is to connect a queue to the exchange and specify the routingKey
channel.basicPublish(exchange, routingKey, props, body);
//This method is to pass information to the specified exchange, exchange is the name of the specified exchange, routingKey is the search method under the exchange, props is the header information, and body is the specific message content

The whole process of incoming message is: first query the exchange to find the corresponding exchange - "if you do not fill in the exchange, specify it to the default exchange, if there is an exchange, send it to the specified exchange - "after sending it to the specified exchange Put into the corresponding queue according to routingKey

The whole process of receiving a message is: create a receiver with the specified queue name, start the thread to listen to the port until the output is received - "If you don't need to return confirmation, continue to listen to the port after processing and wait for new information to come in, if you need to return Confirm that after returning the confirmation, continue to listen and wait for the incoming of new information (if the receiver that needs to confirm the return information cannot return the information, the information will be returned to the queue, that is, the information will not be deleted from the queue)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324696528&siteId=291194637