搭建环境:
win10+Spring Boot 2.1.2+Centos7 RabbitMQ
一:创建工程引入POM文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sfc.mq</groupId>
<artifactId>rabbitmq_server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>rabbitmq_server</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
二:配置application文件(yml文件对格式一定要注意)
info:
description:
name: RabbitMQ
server:
port: 8090
spring:
rabbitmq:
host: #阿里云宿主机IP
port: 5672#端口15672是web界面展示 5672是AMQP端口
username: admin#用户可以自己设置并给权限
password: admin
三:启动类
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class RabbitmqServerApplication {
public static void main(String[] args) {
SpringApplication.run(RabbitmqServerApplication.class, args);
}
}
四:配置类
@Configuration
public class RabbitConfig {
@Bean
public Queue okongQueue() {
return new Queue("message1");
}
}
五:发布消息类
@RestController
@RequestMapping("/sendMQ")
public class SendController {
@Autowired
AmqpTemplate rabbitmqTemplate;
@RequestMapping(value = "/send", method = RequestMethod.GET)
public String send(String msg) {
System.out.println(">>>>>>" + msg);
for(int i = 1;i<1000;i++) {
String message = i+"-"+msg;
rabbitmqTemplate.convertAndSend("message1", message);
}
return "消息:" + msg + ",已发送";
}
}
六:消息消费类
@Component
@RabbitListener(queues = "message1")
public class ConsumerController {
@RabbitHandler
public void process(String message) {
System.out.println("开始处理当前消息:"+message);
}
}
启动运行测试
使用postman请求:localhost:8090/sendMQ/send?msg=admin
查看日志如下: