如何将blob文件发布到GCP Pub/Sub?Java实现相关技术咨询
Java实现GCP Pub/Sub发布Blob文件方案
你当前的代码仅使用了Pub/Sub消息的字符串属性字段存储业务数据,二进制Blob内容需要存入Pub/Sub消息专门的data字节字段传输,具体修改逻辑如下:
核心实现代码
import org.springframework.web.multipart.MultipartFile; import com.google.protobuf.ByteString; import com.google.pubsub.v1.PubsubMessage; // 接口调整为支持表单传参,同时接收业务参数和Blob文件 @PostMapping(value = "/publish/blob") public String publishBlobMessage(@RequestPart("message") MyAppGCPMessage message, @RequestPart("blob") MultipartFile blobFile) throws Exception { // 组装原有业务属性 var attributes = singleFormatAttributes(message); // 新增Blob元信息,方便消费端解析 attributes.put("blob_file_name", blobFile.getOriginalFilename()); attributes.put("blob_content_type", blobFile.getContentType()); attributes.put("blob_size", String.valueOf(blobFile.getSize())); // 将Blob二进制内容写入Pub/Sub消息的data字段 ByteString blobContent = ByteString.copyFrom(blobFile.getBytes()); PubsubMessage messagePub = PubsubMessage.newBuilder() .putAllAttributes(attributes) .setData(blobContent) .build(); repository.publish(messagePub); return "Blob消息发布到GCP Pub/Sub成功"; } private Map<String, String> singleFormatAttributes(MyAppGCPMessage entity) { return Map.of( "id", entity.getId(), "name", entity.getName(), "email",entity.getEmailId() ); }
如果Blob文件是服务本地读取的,不需要通过接口上传,直接读取文件字节传入ByteString.copyFrom()即可。
注意事项
- GCP Pub/Sub单条消息总大小(属性+data字段总和)上限为10MB,超过该大小的Blob不要直接嵌入消息,建议先上传到GCS存储,把文件存储路径等信息放到属性中传递即可。
- 消费端接收消息后,调用
pubsubMessage.getData().toByteArray()即可获取到Blob的二进制数据,转存为对应文件即可。
内容的提问来源于stack exchange,提问作者Hola
相关产品推荐
相关产品推荐

