RabbitMQ消息队列(二):SpringBoot整合之简单模式
1.环境准备
1.1下载安装Erlang&RabbitMQ
Erlang地址:http://www.erlang.org/downloads
RabbitMQ地址:http://www.rabbitmq.com/download.html
1.2 工程准备
1.2.1 工程结构
工程地址:https://toscode.gitee.com/fakefun/rabbitmq.git
1.2.2 核心依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2.生产者
application.yml
指定tomcat端口和rabbitmq地址及登录用户
#tomcat端口
server:
port: 8888
#Rabbitmq的配置
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
virtual-host: /
username: guest
password: guest
RabbitMQConfig
@Configuration
public class RabbitMQConfig {
//队列名称
public static final String ITEM_QUEUE = "simple_queue";
//声明队列
@Bean("simple_queue")
public Queue itemQueue() {
return QueueBuilder.durable(ITEM_QUEUE).build();
}
}
测试controller
@RestController
@Slf4j
public class SimpleQueueController {
@Autowired
private RabbitTemplate rabbitTemplate;
@GetMapping("/simpleQueue")
public String sendMsg(@RequestParam String message) {
String queue = "simple_queue";
log.info("message:{}", message);
rabbitTemplate.convertAndSend(queue, message);
//返回消息
return "OK!";
}
}
请求测试:
http://localhost:8888/simpleQueue?message=test
查看队列:
3.消费者
application.yml
指定tomcat端口和rabbitmq地址及登录用户
#tomcat端口
server:
port: 8800
#Rabbitmq的配置
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
virtual-host: /
username: guest
password: guest
消息消费,指定队列"simple_queue"
@Component
@Slf4j
public class Receiver {
@RabbitListener(queues = "simple_queue")
public void process(String msg) {
log.info("消费端接收msg: " + msg);
}
}
启动服务,查看队列,