生产者
pom依赖如下
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
RabbitMQ配置
# RabbitMQ配置
spring.rabbitmq.host=*.*.*.*
spring.rabbitmq.port=5672
spring.rabbitmq.username=lazyrabbit
spring.rabbitmq.password=password
spring.rabbitmq.virtual-host=/
mail对应实体类
public class Mail implements Serializable {
/**
*
*/
private static final long serialVersionUID = 3062479058855881261L;
private Integer id;
private String to;
private String subject;
private String content;
//getset方法。。。
}
生产者代码实现,通过内置的模板类rabbitTemplate将消息发送到队列中
@Component
public class MailSender {
@Autowired
private RabbitTemplate rabbitTemplate;
public void send(Email email) {
CorrelationData correlationData = new CorrelationData();
correlationData.setId(email.getId().toString());
rabbitTemplate.convertAndSend("mail-exchange", // exchange
"mail.test", // routingKey
email, // 消息实体
correlationData);// 消息id,可以以此取得消息
}
}
测试生产者发送消息
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootRabbitmqApplicationTests {
@Autowired
private MailSender mailSender;
@Test
public void testSend() {
Email e = new Email();
e.setId(123456);
e.setSubject("hello");
e.