RabbitMQ demo
程序员文章站
2022-07-12 12:28:34
...
注:本文项目全是由springboot 构建web项目
服务提供者(生产者)
application.yml
spring:
application:
name: spring-boot-amqp
rabbitmq:
host: 192.168.75.133
port: 5672
username: rabbit
password: 123456
创建队列配置
/**
* 队列配置
* <p>Title: RabbitMQConfiguration</p>
* <p>Description: </p>
*
*/
@Configuration
public class RabbitMQConfiguration {
@Bean
public Queue queue() {
return new Queue("helloRabbit");
}
}
创建消息提供者
@Component
public class HelloRabbitProvider {
@Autowired
private AmqpTemplate amqpTemplate;
public void send() {
String context = "hello" + new Date();
System.out.println("Provider: " + context);
amqpTemplate.convertAndSend("helloRabbit", context);
}
}
创建测试用例
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class AmqpTest {
@Autowired
private HelloRabbitProvider helloRabbitProvider;
@Test
public void testSender() {
for (int i = 0; i < 10; i++) {
helloRabbitProvider.send();
}
}
}
服务消费者
application.yml
spring:
application:
name: spring-boot-amqp-consumer
rabbitmq:
host: 192.168.75.133
port: 5672
username: rabbit
password: 123456
创建消息消费者
@Component
@RabbitListener(queues = "helloRabbit")
public class HelloRabbitConsumer {
@RabbitHandler
public void process(String message) {
System.out.println("Consumer: " + message);
}
}
转载于:https://www.jianshu.com/p/2c501046bacb