1.SpringBoot整合RabbitMQ使用
1.引入依赖:
<!--引入与rabbitmq集成的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.做配置 :application.yml
spring:
application:
name: rabbitmq-springboot
rabbitmq:
host: 192.168.231.141
port: 5672
username: ems
password: 123456
virtual-host: /ems
3.hello world
@SpringBootTest(classes = RabbitmqSpringbootApplication.class)
@RunWith(SpringRunner.class)
@ComponentScan("com.liziyi")
// @EnableRabbit启用@RabbitListener
@EnableRabbit
public class TestRabbitMQ {
// 注入rabbitTemplate
@Autowired
private RabbitTemplate rabbitTemplate;
// hello world
@Test
public void test() {
rabbitTemplate.convertAndSend("hello","hello world");
}
}
// 被工厂扫描道
@Component
// 消费者(声明队列)
@RabbitListener(queuesToDeclare = @Queue("hello"))
public class HelloCustomer {
// 代表通过下面方法取消息
@RabbitHandler
public void receivel(String message) {
System.out.println("message = " + message);
}
}
但是最后执行了。在网页上没有见到新建的队列
4.work
@SpringBootTest(classes = RabbitmqSpringbootApplication.class)
@RunWith(SpringRunner.class)
@ComponentScan("com.liziyi")
// @EnableRabbit启用@RabbitListener
@EnableRabbit
public class TestRabbitMQ {
// 注入rabbitTemplate
@Autowired
private RabbitTemplate rabbitTemplate;
// work
@Test
public void testWork() {
for (int i = 0; i < 10; i++) {
rabbitTemplate.convertAndSend("work","work模型"+i);
}
}
}
@Component
public class WorkCustomer {
@RabbitListener(queuesToDeclare = @Queue("work"))
public void receivel(String message) {
System.out.println("message1 =" +message);
}
@RabbitListener(queuesToDeclare = @Queue("work"))
public void receivel2(String message) {
System.out.println("message2 =" +message);
}
}
5.fanout
@SpringBootTest(classes = RabbitmqSpringbootApplication.class)
@RunWith(SpringRunner.class)
@ComponentScan("com.liziyi")
// @EnableRabbit启用@RabbitListener
@EnableRabbit
public class TestRabbitMQ {
// 注入rabbitTemplate
@Resource
private RabbitTemplate rabbitTemplate;
// fanout 广播
@Test
public void testFanout() {
rabbitTemplate.convertAndSend("logs","","fanout模型");
}
|