Tiven Wang
Wang Tiven July 31, 2017
425 favorite favorites
bookmark bookmark
share share


Message brokers are elements in telecommunication or computer networks where software applications communicate by exchanging formally-defined messages. Message brokers are a building block of message-oriented middleware.

下載本篇完整代碼 Github


添加 Spring AMQP 的 Spring Boot starter 組件


Application Code

Create a RabbitMQ message receiver

首先我們創建一個 Receiver 去接收壞蛋出現的事件, 並讓我們的大英雄去抓住他

public class Receiver {

	public void catchVillains(String villain) {
		try {
			// Assume hero catches the villain in 5 seconds
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
		System.out.println("Catched villain<" + villain + ">");


Register the listener and send a message

RabbitMQ 消息模型的核心概念是: 消息製造者不會直接發送消息給 Queue , 而是發給一個 Exchange , Exchange 負責分發消息給一個或者多個 Queue , 所以消息製造者分本不知道消息發送給了哪個 Queue.

public class MQConfig {

	final static String queueName = "villains-events";

	Queue queue() {
		return new Queue(queueName, false);

	TopicExchange exchange() {
		return new TopicExchange("villains-events-exchange");

	Binding binding(Queue queue, TopicExchange exchange) {
		return BindingBuilder.bind(queue).to(exchange).with(queueName);

	SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
			MessageListenerAdapter listenerAdapter) {
		SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
		return container;

	MessageListenerAdapter listenerAdapter(Receiver receiver) {
		return new MessageListenerAdapter(receiver, "catchVillains");
  • container.setConcurrentConsumers(2); 指定消息接收者同時可以處理2個消息

Spring Boot automatically creates a connection factory and a RabbitTemplate, reducing the amount of code you have to write.

Create a message sender

使用 RabbitTemplate 發送消息給隊列

public class Sender {

	private final RabbitTemplate rabbitTemplate;

	public Sender(RabbitTemplate rabbitTemplate) {
		this.rabbitTemplate = rabbitTemplate;

	public void send(String message) throws Exception {
		System.out.println("Sending villains events...");
		rabbitTemplate.convertAndSend(MQConfig.queueName, message);

Create villains Restful API


private Sender sender;

@RequestMapping(value="/villains", method=RequestMethod.POST)
String home(@RequestParam("message") String message) throws Exception {
    return "Done!";


docker run --rm --name my-rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:management


執行命令 mvn spring-boot:run 運行應用程序。


POST to http://localhost:8080/villains?message=I am here!


Sending villains events...
Catched villain<I am here!>


Deploy to CloudFoundry

部署到 CloudFoundry 之前我們需要創建一個 AMQP 服務,這裡我們使用 Pivotal CloudFoundry Marketplace 裡提供的 CloudAMQP 服務

cf create-service cloudamqp lemur try-cf-amqp

創建成功後,把 CloudAMQP 服務名稱加入 manifest 文件中,全部信息如下

- name: try-cf-message-broker
  buildpack: java_buildpack
  instances: 1
  memory: 200M
  host: try-cf-message-broker
  path: target/try-cf-0.0.1-SNAPSHOT.jar
  - try-cf-amqp


cf push


https://try-cf-message-broker.cfapps.io/villains?message=I am here!

可以查看 CloudFoundry 的應用後台打印信息

cf logs try-cf-message-broker


Similar Posts

  • Try Cloud Foundry 13 - Logs Loggregator is the next generation system for aggregating and streaming logs and metrics from all of the user apps and system components in an Elastic Runtime deployment. Loggregator uses Google's protocol buffers along with gRPC to deliver logs.
  • Try Cloud Foundry 12 - Config Server Config Server for Pivotal Cloud Foundry (PCF) is an externalized application configuration service, which gives you a central place to manage an application’s external properties across all environments.
  • Try Cloud Foundry 11 - Autoscaler Autoscaler
  • Try CloudFoundry Try CloudFoundry
  • Try Cloud Foundry 10 - Service Discovery Service Registry for Pivotal Cloud Foundry (PCF) provides your applications with an implementation of the Service Discovery pattern, one of the key tenets of a microservice-based architecture. Trying to hand-configure each client of a service or adopt some form of access convention can be difficult and prove to be brittle in production. Instead, your applications can use the Service Registry to dynamically discover and call registered services.
  • Try Cloud Foundry 8 - Spring Cloud Connector Spring Cloud Connectors simplifies the process of connecting to services and gaining operating environment awareness in cloud platforms such as Cloud Foundry and Heroku, especially for Spring applications. It is designed for extensibility: you can use one of the provided cloud connectors or write one for your cloud platform, and you can use the built-in support for commonly-used services (relational databases, MongoDB, Redis, RabbitMQ) or extend Spring Cloud Connectors to work with your own services.


Back to Top