基于Springboot的RabbitMQ使用
2021-01-16 本文已影响0人
攻城老狮
一 普通的收发字符串类型数据
- 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-test</artifactId>
<scope>test</scope>
</dependency>
- 添加配置
server:
port: 8001
spring:
application:
name: producer
rabbitmq:
host: 192.168.44.142
port: 5672
virtual-host: host1
username: yorick
password: 199748
- 发送消息(生产者)
@Service
public class SendMsgService {
@Autowired
private AmqpTemplate amqpTemplate;
public void sendMsg(String msg){
//简单模式,工作模式
amqpTemplate.convertAndSend("","queue1",msg);
//订阅模式
//amqpTemplate.convertAndSend("ex1","",msg);
//路由模式
//amqpTemplate.convertAndSend("ex2","k2",msg);
}
}
- 测试发送消息(生产者)
@SpringBootTest
@RunWith(SpringRunner.class)
public class SendMsgServiceTest {
@Autowired
private SendMsgService service;
@Test
public void testSendMsg(){
service.sendMsg("Hello queue");
}
}
- 接收消息(消费者)
@Service
@RabbitListener(queues = "queue1")
public class ReceiveMsgService {
@Autowired
private AmqpTemplate amqpTemplate;
@RabbitHandler
public void receiveMsg(String msg){
System.out.println("receive msg: "+ msg);
}
}
二 收发对象类型数据
2.1 直接发送序列化的对象
注意:
- bean实现序列化接口
- 生产者消费者的bean包名必须一致
- 实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
private String username;
private String password;
}
- 发送消息(生产者)
@Service
public class SendMsgService {
@Autowired
private AmqpTemplate amqpTemplate;
public void sendMsg(User user){
amqpTemplate.convertAndSend("","queue1",user);
}
}
- 测试发送消息(生产者)
@SpringBootTest
@RunWith(SpringRunner.class)
public class SendMsgServiceTest {
@Autowired
private SendMsgService service;
@Test
public void testSendMsg(){
User user = new User();
user.setUsername("yorick");
user.setPassword("199748");
service.sendMsg(user);
}
}
- 接收消息(消费者)
@Service
@RabbitListener(queues = "queue1")
public class ReceiveMsgService {
@Autowired
private AmqpTemplate amqpTemplate;
@RabbitHandler
public void receiveMsg(User user){
System.out.println("receive msg: "+ user);
}
}
2.2 JSON字符串实现
- 发送消息(生产者),将对象转换为JSON字符串
@Service
public class SendMsgService {
@Autowired
private AmqpTemplate amqpTemplate;
public void sendMsg(User user) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String userString = mapper.writeValueAsString(user);
amqpTemplate.convertAndSend("","queue1",userString);
}
}
- 接收消息(消费者),将JSON字符串转换为对象
@Service
@RabbitListener(queues = "queue1")
public class ReceiveMsgService {
@Autowired
private AmqpTemplate amqpTemplate;
@RabbitHandler
public void receiveMsg(String userString) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(userString, User.class);
System.out.println("receive msg: "+ user);
}
}