RabbitMQ Article 5: Spring integrates RabbitMQ and rabbitmq Article 5
The previous sections explain how to use rabbitMq. This section describes how to integrate spring with rabbitmq.
First introduce the configuration file org. springframework. amqp, as shown below:
<dependency> <groupId>org.springframework.amqp</groupId> <artifactId>spring-rabbit</artifactId> <version>1.6.0.RELEASE</version> </dependency>
1. Configure the public part of the consumer and the Creator
<Rabbit: connection-factory id = "connectionFactory" host = "$ {rabbit. hosts} "port =" $ {rabbit. port} "username =" $ {rabbit. username} "password =" $ {rabbit. password} "virtual-host =" $ {rabbit. virtualHost} "channel-cache-size =" 50 "/> <rabbit: admin connection-factory =" connectionFactory "/> <! -- Define Message queue --> <rabbit: queue name = "spittle. alert. queue.1 "durable =" true "auto-delete =" false "/> <rabbit: queue name =" spittle. alert. queue.2 "durable =" true "auto-delete =" false "/> <rabbit: queue name =" spittle. alert. queue.3 "durable =" true "auto-delete =" false "/> <! -- Bind a queue --> <rabbit: fanout-exchange id = "spittle. fanout "name =" spittle. fanout "durable =" true "> <rabbit: bindings> <rabbit: binding queue =" spittle. alert. queue.1 "> </rabbit: binding> <rabbit: binding queue =" spittle. alert. queue.2 "> </rabbit: binding> <rabbit: binding queue =" spittle. alert. queue.3 "> </rabbit: binding> </rabbit: bindings> </rabbit: fanout-exchange>
Ii. Configuration Builder
<Import resource = "amqp-share.xml"/> <! -- Create a message queue template --> <rabbit: template id = "rabbitTemplate" connection-factory = "connectionFactory" exchange = "spittle. fanout "message-converter =" jsonMessageConverter "> </rabbit: template> <bean id =" jsonMessageConverter "class =" org. springframework. amqp. support. converter. jsonMessageConverter "> </bean>
3. Producer Program
public class Spittle implements Serializable { private Long id; private Spitter spitter; private String message; private Date postedTime; public Spittle(Long id, Spitter spitter, String message, Date postedTime) { this.id = id; this.spitter = spitter; this.message = message; this.postedTime = postedTime; } public Long getId() { return this.id; } public String getMessage() { return this.message; } public Date getPostedTime() { return this.postedTime; } public Spitter getSpitter() { return this.spitter; }}
public class ProducerMain { public static void main(String[] args) throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("amqp/amqp-producer.xml"); AmqpTemplate template = (AmqpTemplate) context.getBean("rabbitTemplate"); for (int i = 0; i < 20; i++) { System.out.println("Sending message #" + i); Spittle spittle = new Spittle((long) i, null, "Hello world (" + i + ")", new Date()); template.convertAndSend(spittle); Thread.sleep(5000); } System.out.println("Done!"); }}
In the convertAndSend method, the first parameter is the switch name by default, the second parameter is the route name, and the third parameter is the data we send. Now we start the program, and the effect is as follows:
Fourth: Consumer Program
First, write a code to listen to the producer's sending information.
/** * Created by Administrator on 2016/11/18. */public class SpittleAlertHandler implements MessageListener { @Override public void onMessage(Message message) { try { String body=new String(message.getBody(),"UTF-8"); System.out.println(body); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }}
Be sure to implement MessageListener. We only need to get the body of the message and use json to convert the program we need (for example, we can send a map, map storage method and object, in this way, we can call different programs to run through reflection ).
Below we configure the consumer
<import resource="amqp-share.xml"/> <rabbit:listener-container connection-factory="connectionFactory"> <rabbit:listener ref="spittleListener" method="onMessage" queues="spittle.alert.queue.1,spittle.alert.queue.3,spittle.alert.queue.2"/> </rabbit:listener-container> <bean id="spittleListener" class="com.lp.summary.rabbitmq.impl.SpittleAlertHandler"/>
Among them, spittleListener is the listener program, method is the execution method, queues is the queue we listen to, and multiple queues can be separated by commas (,) (because we use distribution, therefore, the messages obtained from the three queues are the same. I put them in a listener for convenience. In fact, we can write three consumers, each of which listens to one queue)
Now you only need to start the program to run
public class ConsumerMain { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("amqp/amqp-consumer.xml"); }}
Of course, direct is similar to the above, but this is based on route matching. First, the data is sent to the switch, then the route and queue are bound, and the queue is found through the switch id and route origin. Below are some main configurations.
<Rabbit: queue id = "spring-test-queue1" durable = "true" auto-delete = "false" exclusive = "false" name = "spring-test-queue1"> </rabbit: queue> <rabbit: queue name = "spring-test-queue2" durable = "true" auto-delete = "false" exclusive = "false"> </rabbit: queue> <! -- Switch definition --> <! -- Rabbit: direct-exchange: defines the exchange mode as direct, which means that the message will be forwarded only when it exactly matches a specific route key. Rabbit: binding: Set the key matching the Message queue --> <rabbit: direct-exchange name = "$ {rabbit. exchange. direct} "durable =" true "auto-delete =" false "id =" $ {rabbit. exchange. direct} "> <rabbit: bindings> <rabbit: binding queue =" spring-test-queue1 "key =" spring. test. queueKey1 "/> <rabbit: binding queue =" spring-test-queue2 "key =" spring. test. queueKey2 "/> </rabbit: bindings> </rabbit: direct-exchange> <! -- Spring template declaration --> <rabbit: template exchange = "$ {rabbit. exchange. direct} "id =" rabbitTemplate "connection-factory =" connectionFactory "message-converter =" jsonMessageConverter "> </rabbit: template> <! -- Convert the message object to json --> <bean id = "jsonMessageConverter" class = "org. springframework. amqp. support. converter. JsonMessageConverter"> </bean>
The following is the consumer monitoring configuration
<rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto"> <rabbit:listener queues="spring-test-queue1" method="onMessage" ref="queueListenter"></rabbit:listener> </rabbit:listener-container> <rabbit:listener-container connection-factory="connectionFactory" acknowledge="auto"> <rabbit:listener queues="spring-test-queue2" method="onMessage" ref="queueListenter"></rabbit:listener> </rabbit:listener-container>
Below is the program
public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext-rabbitmq-producer.xml"); MQProducer mqProducer=(MQProducer) context.getBean("mqProducer"); mqProducer.sendDateToQueue("spring.test.queueKey1","Hello World spring.test.queueKey1"); mqProducer.sendDateToQueue("spring.test.queueKey2","Hello World spring.test.queueKey2"); }
The actual situation may require us to separate the consumer program and generate the program. Of course, there are also Server Load balancer configurations in spring. I will not introduce them here.