There are many tutorials on the installation method of rabbitMQ on the Internet, so I won't repeat it here.
Use rabbitMQ to transfer strings and objects on springboot. The example given in this article is to transfer objects and strings between two different projects.
rabbitMQ dependency (same configuration in both projects):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
pom configuration file (same configuration in both projects):
spring.application.name: demo1 //Project name spring.rabbitmq.host: 192.168.1.111 //Write your own ipspring.rabbitmq.port: 5672spring.rabbitmq.username: guestspring.rabbitmq.password: guestspring.rabbitmq.virtual-host: /spring.rabbitmq.publisher-confirms: truespring.rabbitmq.publisher-returns: truespring.rabbitmq.template.mandatory: true
Character transfer mutual transmission (the topic type used in this example)
1>. First, write the configuration file in the producer (project A), where the queue queue is generated, the switch exchange and binding is performed
import org.springframework.amqp.core.Binding;import org.springframework.amqp.core.BindingBuilder;import org.springframework.amqp.core.Queue;import org.springframework.amqp.core.TopicExchange;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * @Author:fdh * @Description: * @Date: Create in 16:13 2017/12/22 */@Configurationpublic class senderConfigration { /** *@Description: Create a new queue topic.messages *@Data:16:14 2017/12/22 */ @Bean(name = "messages") public Queue queueMessages(){ return new Queue("topic.messages"); } /** *@Description: Define the switch*@Data:16:15 2017/12/22 */ @Bean public TopicExchange exchange(){ return new TopicExchange("exchange"); } /** *@Description: The switch binds the queue messages binds the switch with topic.messages *@Data:16:18 2017/12/22 */ @Bean Binding bindingExchangeMessages(@Qualifier("messages") Queue queueMessages,TopicExchange exchange){ return BindingBuilder.bind(queueMessages).to(exchange).with("topic.messages"); }}2>. In the second step (item A), the producer sends the message to the message queue.
/** * @Author:fdh * @Description: * @Date: Create in 14:15 2017/12/22 */@Controllerpublic class RabbitController { @Autowired private AmqpTemplate amqpTemplate; @RequestMapping("/sendss") public void send1(){ amqpTemplate.convertAndSend("exchange","topic.messages","hello topic.messages RabbitMQ"); }}3>. Next, write a listener on the consumer (project B) side. The switch will place the message produced by the producer into the matching message queue based on the bound routing key (topic.messages). The listener will listen to the corresponding message queue to obtain messages routed to the message queue.
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.amqp.rabbit.annotation.RabbitListener;/** * @ Author:fdh * @ Description: Message queue listener* @ Date: Create in 14:19 2017/12/22 */@Componentpublic class Receiver { @RabbitListener(queues = "topic.messages") public void process2(String str1) throws ClassNotFoundException{ System.out.println("messages:"+str1); System.out.println(Thread.currentThread().getName()+"Received a message from the topic.message queue: "+str1); } In this way, a simple string transmission is written. Let’s open the mapping just defined: 192.168.1.111:8080/sendss
You will see a printed message in the console window on the consumer side
The above is a simple example of transmitting strings.
2. The following focuses on the transmission of objects between consumers and producers.
The transmission of objects must be serialized in the producer (A), that is, the object is converted into a byte array for transmission, and in the consumer, the converted byte array is deserialized into an object. There are many methods for serialization and deserialization, and here we use Java's Serializable interface
1>. Create entity classes in projects of producer (project A) and consumer (project B).
! Notice! : Create a new entity class Boy.java The entity class must be consistent in the position of projects A and B, that is, the package name must be consistent. In this project, Boy.java is in projects A and B: import com.fengdonghao.shiro.bean.Boy;
Entity classes must also be consistent.
package com.fengdonghao.shiro.bean;import javax.persistence.*;import java.io.Serializable;/** * @Author:fdh * @Description: * @Date: Create in11:14 2017/12/16 */@Entitypublic class Boy implements Serializable{ private static final long serialVersionUID=1L; @Id @GeneratedValue private int id; private String name; private int age; @Override public String toString() { return "Boy{" + "age=" + age + ", id=" + id + ", name='" + name + '/'' + '}'; }//The getter and setter methods are omitted here} 2>. Configure the message queue, switch, and bind binding in the producer (A), and the first step in Example 1 is the same
3>. Write another mapping in RabbitController.java in Producer (A), as follows
@RequestMapping("/send") public void sendMessage() { Boy boy= new Boy(); boy.setName("tim"); boy.setAge(11); System.out.println(boy); //The following is the serialization operation//Write Obj to File ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream(new File("E://WebPackage//a.txt")));//Temporarily store the serialized byte array in this directory oos.writeObject(boy); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(oos); } rabbitMQService.send("Object has been serialized"); 4>. Deserialize the byte array in consumer (B).
In Receiver, rewrite the listener for example 1 key
@RabbitListener(queues = "topic.messages") public void process2(String str1) { System.out.println(Thread.currentThread().getName()+"Receive a message from the topic.message queue: "+str1+" and deserialize"); File file = new File("E://WebPackage//a.txt");//The paths between consumers and producers must be consistent before the file can be read and parsed. ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream(file)); Boy newUser = (Boy) ois.readObject(); System.out.println("Desequence:"+newUser); System.out.println("Desequence:"+newUser.getName()); System.out.println("Desequence:"+newUser.getName()); System.out.println("Desequence after getAge"+newUser.getAge()); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(ois); try { FileUtils.forceDelete(file); } catch (IOException e) { e.printStackTrace(); } } System.out.println("messages:"+str1); } Verification mapping: ip: 8080/send
The results are as follows:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.