spring boot整合rabbitmq(一)——消息發佈與訂閱

1.pom,xml引入下面的架,版本本身選java

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

  <version>2.1.3.RELEASE</version>app

</dependency>異步

2.application.yml,配置鏈接rabbmitmq鏈接信息spring-boot

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

3.建立隊列code

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

4.發佈消息xml

@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.訂閱消息blog

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

 注意:消息發佈了,這個方法會被異步調用rabbitmq

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 20192019-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 already2019-06-05 15:18:05.584 INFO 10124 --- [ Thread-2] o.s.a.r.l.SimpleMessageListenerContainer : Shutdown ignored - container is not active already2019-06-05 15:18:05.584 INFO 10124 --- [ Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'

相關文章
相關標籤/搜索