springboot使用rabbitmq发送MultipartFile文件
时间: 2025-01-24 13:58:51 浏览: 42
### 使用 Spring Boot 和 RabbitMQ 发送 MultipartFile 类型文件
为了实现通过 `RabbitMQ` 发送 `MultipartFile` 文件,在 `Spring Boot` 应用程序中可以采用如下方法:
#### 准备工作
确保已经安装并运行了 `RabbitMQ Server` 服务端[^1]。接着,创建一个新的 `Spring Boot` 工程,并引入必要的依赖项。
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!-- 如果需要处理文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
```
#### 配置 RabbitMQ 连接工厂和队列声明
定义连接到 `RabbitMQ` 的配置类来设置交换机、队列以及绑定关系。
```java
@Configuration
public class RabbitConfig {
@Bean
public Queue fileQueue() {
return new Queue("file_queue", false);
}
@Bean
DirectExchange exchange() {
return new DirectExchange("file_exchange");
}
@Bean
Binding binding(Queue fileQueue, DirectExchange exchange) {
return BindingBuilder.bind(fileQueue).to(exchange).with("file_routing_key");
}
}
```
#### 创建消息生产者用于发送文件
编写控制器接收前端传来的文件流数据并通过 `AMQP Template` 将其转换成字节数组形式的消息体推送到指定队列里去。
```java
@RestController
@RequestMapping("/api/file")
public class FileController {
private final AmqpTemplate amqpTemplate;
public FileController(AmqpTemplate amqpTemplate){
this.amqpTemplate = amqpTemplate;
}
@PostMapping(value="/sendFile", consumes="multipart/form-data")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException{
byte[] bytes = file.getBytes();
String fileName = file.getOriginalFilename();
Map<String,Object> messageBody=new HashMap<>();
messageBody.put("fileName",fileName);
messageBody.put("content",bytes);
ObjectMapper objectMapper = new ObjectMapper();
String jsonMessage=objectMapper.writeValueAsString(messageBody);
amqpTemplate.convertAndSend("file_exchange","file_routing_key",jsonMessage);
return ResponseEntity.ok("Successfully sent!");
}
}
```
此代码片段展示了如何将 `MultipartFile` 转化为 JSON 字符串格式再作为消息主体的一部分发送给 `RabbitMQ` 中的特定队列[^2]。
阅读全文
相关推荐









