简介
RabbitMQ与Spring boot 整合还是比较简单的,在整合中有两个对象是很重要的,RabbitAdmin、RabbitTemplate。
- RabbitAdmin:其提供了 RabbitMQ 中声明交换机、声明队列、绑定交换机和队列,以及绑定路由 Key 等其他 API。
- RabbitTemplate:在 Spring 中通过 RabbitTemplate 来操作消息并发送和监听消息。
这里暂时不对上述两个对象进行详细介绍,只是做一个整合的简单例子。
maven 配置
<?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 https://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>1.5.16.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ced</groupId>
<artifactId>rabbitmq-springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>rabbitmq-springboot</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<swagger2.version>2.8.0</swagger2.version>
</properties>
<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>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger2.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger2.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
代码
创建一个项目 rabbitmq-springboot。如图
生产者代码
application.yml
# 端口号
server:
port: 8080
#
spring:
rabbitmq:
username: admin
password: admin
virtual-host: /
host: localhost
port: 5672
SimpleRabbitConfig.java
package com.ced.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 配置
*
* @author 崔二旦
* @since 昨天
*/
@Configuration
public class SimpleRabbitConfig {
/**
* 交换机
*/
public static final String EXCHANGE_NAME = "order_exchange";
@Bean
public Queue simpleQueue() {
return new Queue("simple_queue", true);
}
@Bean
public DirectExchange simpleDirectExchange() {
return new DirectExchange(EXCHANGE_NAME, true, false);
}
@Bean
public Binding simpleBinding() {
return BindingBuilder.bind(simpleQueue()).to(simpleDirectExchange()).with("");
}
}
Swagger2.java
package com.ced.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Swagger 配置文件
*
* @author Cuierdan
* @since 2021年12月7日
*/
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("通用API接口文档")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.ced.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("接口文档")
.description("接口文档!")
.termsOfServiceUrl("http://localhost:8080/")
.version("2.0")
.build();
}
}
OrderController.java
package com.ced.controller;
import com.ced.service.OrderSimpleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* 订单管理 控制器
* 简单模式
*
* @author 崔二旦
* @since 昨天
*/
@RestController
@RequestMapping("/order")
@Api(value = "订单管理控制器", description = "订单管理控制器")
public class OrderController {
/** 成功状态值 */
public static final String STATUS_SUCCESS_CODE = "1";
@Resource
private OrderSimpleService orderSimpleService;
/**
* 创建订单
*
* @param orderName 订单名称
* @param amount 数量
* @return 创建状态
*/
@ApiOperation(value = "创建订单(简单模式)", notes = "创建订单(简单模式)")
@ApiImplicitParams({
@ApiImplicitParam(name = "orderName", value = "订单名称", dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "amount", value = "数量", dataType = "Integer", paramType = "query")})
@GetMapping(value = "/simple/add")
public String orderSimpleAdd(String orderName, int amount) {
String status = orderSimpleService.orderAdd(orderName, amount);
if(STATUS_SUCCESS_CODE.equals(status)){
return "成功";
}
return "失败";
}
}
OrderSimpleService.java
package com.ced.service;
/**
* 订单管理 服务接口
* 简单模式
*
* @author 崔二旦
* @since 昨天
*/
public interface OrderSimpleService {
/**
* 新增订单
* @param orderName 订单名称
* @param amount 订单数量
* @return 下单状态
*/
String orderAdd(String orderName, int amount);
}
OrderSimpleServiceImpl.java
package com.ced.service.impl;
import com.ced.service.OrderSimpleService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* 订单管理 服务接口实现类
* 简单模式
*
* @author 崔二旦
* @since 昨天
*/
@Service
public class OrderSimpleServiceImpl implements OrderSimpleService {
@Resource
private RabbitTemplate rabbitTemplate;
/**
* 交换机
*/
public static final String EXCHANGE_NAME = "order_exchange";
@Override
public String orderAdd(String orderName, int amount) {
//生成单号
String orderId = UUID.randomUUID().toString();
//模拟处理订单信息
Map<String, Object> orderMap = new HashMap<>(3);
orderMap.put("orderId", orderId);
orderMap.put("orderName", orderName);
orderMap.put("amount", amount);
this.rabbitTemplate.convertAndSend(EXCHANGE_NAME,"", orderMap);
System.out.println("消息发送成功");
return "1";
}
}
消费者代码
该消费者代码是与生产者写到了一个项目中,因为生产者和消费者可以是一个程序。
SimpleConsumer.java
package com.ced.consumer;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* 消费者
*
* @author 崔二旦
* @since 昨天
*/
@RabbitListener(queues = "simple_queue")
@Component
public class SimpleConsumer {
@RabbitHandler
public void receive(Map<String, Object> message) {
System.out.println(message.get("orderId"));
}
}
请求页面
结果
注
以上就是RabbitMQ与Spring boot 整合的一个简单的例子,后续会编写一个相对完整的项目,分享到崔二旦 (cuierdan) - Gitee.com里 。
源码
崔二旦: RabbitMQ与Spring boot简单整合https://gitee.com/cuierdan/build/tree/master/rabbitmq-springboot-simple