spring boot整合rabbitmq(一)——消息发布与订阅

1.pom,xml引入下面的架,版本自己选

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-amqp</artifactId>

  <version>2.1.3.RELEASE</version>

</dependency>

2.application.yml,配置连接rabbmitmq连接信息

spring:
  rabbitmq:
  host: localhost
  port: 5672
  username: admin
  password: admin

3.创建队列

@Configuration
public class RabbitMqConfig {
	
	@Bean
	public Queue helloWorldQueue() {
		return new Queue("helloWorld_queue_test1",true);
	}
}

4.发布消息

@Component
public class Sender {
	@Autowired
	private RabbitTemplate rabbitTemplate; 
	
	/**
	 * 发送消息
	 */
	public void send() {
		String message = "message" + new Date();
		rabbitTemplate.convertAndSend("helloWorld_exchange_test1","hello_world_route_key",message);
	}
}

5.订阅消息

@RabbitListener(queues = "helloWorld_queue_test1")
@Component
public class Receiver {
	
	/**
	 * 消费
	 * @param message
	 */
	@RabbitHandler
	public void helloWorld(String message) {
		System.out.println("Receiver1:" + message);
	}
}

 注意:消息发布了,这个方法会被异步调用

6.测试

pom.xml需要引入如下包:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <version>2.1.3.RELEASE</version>

  <scope>test</scope>

</dependency>

@RunWith(SpringRunner.class)
@SpringBootTest(classes = RabbitMqServerApplication.class)
public class SendTest {
	@Autowired
	private Sender sender;
	
	@Test
	public void testSend() {
		sender.send();
	}
}

发送的消息成功被消费

控制台输出

Receiver1:messageWed Jun 05 15:18:04 CST 2019
2019-06-05 15:18:04.846 INFO 10124 --- [ Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2019-06-05 15:18:04.849 INFO 10124 --- [ Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Waiting for workers to finish.
2019-06-05 15:18:05.581 INFO 10124 --- [ Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Successfully waited for workers to finish.
2019-06-05 15:18:05.584 INFO 10124 --- [ Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Shutdown ignored - container is not active already
2019-06-05 15:18:05.584 INFO 10124 --- [ Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Shutdown ignored - container is not active already
2019-06-05 15:18:05.584 INFO 10124 --- [ Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'

 

 

转载于:https://www.cnblogs.com/thomas-seven/p/10979831.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值