对于RabbitMQ的开发,Spring方法提供了更为方便的操作.
Spring官网介绍: Spring AMQP
RabbitMQ官网介绍: RabbitMQ tutorial - "Hello World!" | RabbitMQ
引入依赖
为了方便测试也引入SpringWeb依赖.
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
添加配置
#配置RabbitMQ的基本信息
spring:
rabbitmq:
host: # IP地址
port: 5672 #端口号 默认5672
username: #用户名
password: #密码
virtual-host: #虚拟主机
# 以上写法也可以整合成下面这种写法
# addresses: amqp://用户名:密码@IP地址:端口号/虚拟主机
工作模式代码
相关常量
public class Constants {
//工作队列模式
public static final String WORK_QUEUE = "work.queue";
}
相关配置
import com.example.rabbitmqspringboot.constant.Constants;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
// 工作队列模式
// 工作队列交给Spring管理
@Bean("workQueue")
public Queue workQueue(){
return QueueBuilder.durable(Constants.WORK_QUEUE).build();
}
}
生产者
import com.example.rabbitmqspringboot.constant.Constants;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/producer")
@RestController
public class ProducerController {
// 引入RabbitTemplate 这是Spring Boot提供的RabbitMQ客户端相关操作
@Autowired
private RabbitTemplate rabbitTemplate;
// 工作模式的生产者代码
@RequestMapping("/work")
public String work(){
for (in