用 Camel 把图片上传至 IPFS 并返回 CID

解读

在国内面试场景里,这道题并不是让你背诵 IPFS 白皮书,而是考察“用 Camel 把非标准协议封装成可复用组件”的能力。
面试官真正想听的是:

  1. 你能否把“上传文件→拿到 CID”抽象成一条标准 Camel 路由;
  2. 你能否在不改业务代码的前提下,把 IPFS 节点地址、超时、重试、Content-Type 等参数外部化;
  3. 你能否让这条路由同时支持本地网关、私有集群和公共网关,以应对国内监管与合规要求;
  4. 你能否在返回 CID 的同时,把图片指纹、文件大小、上传耗时自动写进公司已有的审计 Topic,方便后续追溯。

一句话:Camel 只是“外壳”,路由设计、容错策略、合规埋点才是得分点。

知识点

  1. 自定义 Camel 组件(IPFSComponent):继承 DefaultComponent,注册 IPFSProducer,把 add(file) 与 cid 解析封装成 Endpoint。
  2. 幂等写:RedisIdempotentRepository 防止同一张图片因重试被多次 Pin,浪费节点存储。
  3. 国内网络容错:通过 CircuitBreaker 配置 3 次重试 + 2 s 退避,识别“连接被重置”异常并自动切换备用网关。
  4. 内容合规:在 Producer 里先计算 SHA-256,调用内部风控服务做敏感指纹比对,命中则直接拒绝并抛出 CamelException,路由进入死信队列。
  5. 参数外部化:使用 Camel 的 PropertiesComponent,把 ipfs.api.multiaddr、gateway.url、pin.timeout 放到 Nacos,支持灰度发布。
  6. 返回格式:使用 Processor 把 CID 封装成统一 REST 响应,字段包括 cid、size、sha256、timestamp,方便前端回显。
  7. 监控:在路由末尾 to("micrometer:timer:ipfs.upload"),指标自动落入公司 Prometheus,面试时可提到“后续可接入 Grafana 大盘”。

答案

下面给出可直接落地的 Camel 路由(YAML 风格,Spring Boot 3.x,兼容国内私有 IPFS 集群)。
所有敏感参数已外部化,符合等保要求。

camel:
  springboot:
    name: ipfs-uploader
  component:
    ipfs:
      multiaddr: ${ipfs.api.multiaddr:/ip4/192.168.10.30/tcp/5001}
      gateway: ${ipfs.gateway.url:https://ipfs-gateway.company.cn}
      timeout: ${ipfs.pin.timeout:10s}
      max-retries: 3
      retry-delay: 2s

# 路由
- route:
    id: upload-image
    from:
      uri: "jetty:http://0.0.0.0:8080/upload"
      parameters:
        httpMethodRestrict: POST
    onException:
      - exception: "java.net.SocketException"
        handled: true
        maximumRedeliveries: 3
        redeliveryDelay: 2000
        onRedelivery:
          bean:
            ref: switchGatewayProcessor   # 切换备用网关
        setBody:
          simple: '{"code":500,"msg":"网络异常,请稍后重试"}'
    pipeline:
      # 1. 校验图片格式
      - to: "validator:file:schema/image.json"
      # 2. 计算 SHA-256 并做敏感内容比对
      - processRef: complianceProcessor
      # 3. 幂等判断
      - idempotentConsumer:
          header: "sha256"
          messageIdRepositoryRef: "redisIdempotentRepo"
      # 4. 上传 IPFS
      - to: "ipfs:add?pin=true"
      # 5. 封装返回
      - processRef: wrapResponseProcessor
      # 6. 审计埋点
      - to: "kafka:topic-ipfs-audit"

核心 Java 片段(Producer 节选):

public class IPFSProducer extends DefaultProducer {
    private final IPFS ipfs;
    public void process(Exchange exchange) throws Exception {
        byte[] bytes = exchange.getIn().getBody(byte[].class);
        NamedStreamable.ByteArrayStreamable stream = new NamedStreamable.ByteArrayStreamable(bytes);
        List<MerkleNode> nodes = ipfs.add(stream, true); // pin=true
        String cid = nodes.get(0).hash.toString();
        exchange.getMessage().setHeader("CID", cid);
        exchange.getMessage().setBody(cid);
    }
}

部署后调用:
curl -F "file=@cat.jpg" http://localhost:8080/upload
返回:
{"cid":"QmXyZ...","size":1024768,"sha256":"abc123...","ts":1719300000}

即完成“图片上传→IPFS→返回 CID”全链路,且具备重试、幂等、合规、监控等企业级能力。

拓展思考

  1. 国内监管:公共 IPFS 网关常被限速或封禁,生产环境必须自建私有集群,并通过VPN 加密通道与业务网打通;Camel 路由里可用 LoadBalance 把流量按比例切到多组节点,实现“多地多活”。
  2. 图片秒传:在幂等校验前增加FastCDC 分片逻辑,先计算 root-CID,若集群已存在则直接返回,节省 90% 带宽;该逻辑可做成 Camel 的另一个组件 ipfs-dedup,让业务无感知。
  3. 链上存证:返回 CID 后,可再走一条子路由把 CID、SHA-256、业务订单号写入长安链或Fabric 联盟链,实现“图片不可篡改”的司法存证;Camel 已有 blockchain 组件,可直接 to("fabric:invoke"),面试时提到这一点可体现你对国内合规链的了解。
  4. 大文件分片上传:单张图片超过 100 MB 时,可改用 ipfs files write --flush 的 Chunk 模式;Camel 路由里用 Splitter EIP 按 4 MB 切片,边上传边返回进度事件,通过 Server-Sent Events 推给前端,展示“99% 完成”的实时体验。