0%

RabbitMQ入门案例

pom.xml

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

Sender

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 消息发送者
*/
@Component
public class Sender {

@Autowired
private AmqpTemplate rabbitAmqpTemplate;

/**
* 发送消息方法
*/
public void send(String msg) {
//向消息队列中发送消息
//参数一: 队列名称
//参数二: 消息
this.rabbitAmqpTemplate.convertAndSend("hello-queue", msg);
}
}

Receiver

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.swifter;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
* 消息接受者
*/
@Component
public class Receiver {

/**
* 接收消息的方法, 采用消息队列监听机制
* @param msg
*/
@RabbitListener(queues = "hello-queue")
public void process(String msg) {
System.out.println("receiver: " + msg);
}

}

HelloController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import com.swifter.Sender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

@Autowired
private Sender sender;

@RequestMapping("quick")
public String quick() {
sender.send("hello world");
return "Hello world!";
}
}

–EOF–