Java 后端 / 系统课时

封装第三方接口适配器

封装第三方接口适配器

第三方接口往往在鉴权方式、字段命名、错误码和重试规则上各不相同。本课用一个“统一短信发送接口”完成适配器封装,使业务层只依赖稳定的领域模型,并把供应商差异限制在基础设施层。

学习目标

  • 设计与供应商无关的调用接口和请求、结果模型
  • 在适配器内集中处理鉴权、数据转换与错误映射
  • 通过替换实现接入新的供应商,而不修改业务代码

先划清适配器边界

业务层真正关心的是“向某个手机号发送某个模板”,而不是供应商要求的签名算法、字段名或响应结构。因此先定义稳定端口 SmsGateway,再由供应商适配器实现它。

适配器应承担四类职责:把领域请求转换为供应商请求;附加密钥、令牌或签名;把供应商响应转换为统一结果;把超时、限流和业务拒绝映射为系统可识别的异常。重试策略可以放在适配器外层,但必须基于统一异常类型判断。

第三方接口适配器的调用与转换链路

定义统一端口和领域模型

下面示例使用 Java record 表达不可变请求与结果,并用枚举统一失败原因。业务代码只认识这些类型,不直接依赖供应商 DTO。

java
package com.example.integration.sms;

public interface SmsGateway {
    SmsResult send(SmsCommand command);
}

record SmsCommand(String mobile, String templateCode, String content) {
}

record SmsResult(String requestId, Status status) {
    enum Status {
        ACCEPTED, REJECTED
    }
}

class SmsGatewayException extends RuntimeException {
    private final ErrorType errorType;

    SmsGatewayException(ErrorType errorType, String message, Throwable cause) {
        super(message, cause);
        this.errorType = errorType;
    }

    ErrorType getErrorType() {
        return errorType;
    }

    enum ErrorType {
        TIMEOUT, RATE_LIMITED, AUTHENTICATION_FAILED, REMOTE_ERROR
    }
}

这些类型的关键价值是稳定。即使供应商把 mobile 改成 phone_number,或者把成功码从 0 改成 SUCCESS,变化也只发生在适配器中。

实现供应商适配器

以下示例使用 Spring Framework 的 RestClient。它把统一命令转换为供应商 JSON,通过请求头传递令牌,并把 HTTP 状态和响应字段映射回领域结果。

java
package com.example.integration.sms;

import java.net.SocketTimeoutException;
import org.springframework.http.HttpStatusCode;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientException;

public final class VendorASmsAdapter implements SmsGateway {
    private final RestClient client;
    private final String token;

    public VendorASmsAdapter(RestClient.Builder builder, String baseUrl, String token) {
        this.client = builder.baseUrl(baseUrl).build();
        this.token = token;
    }

    @Override
    public SmsResult send(SmsCommand command) {
        VendorRequest request = new VendorRequest(
                command.mobile(), command.templateCode(), command.content());

        try {
            VendorResponse response = client.post()
                    .uri("/v1/messages")
                    .header("Authorization", "Bearer " + token)
                    .body(request)
                    .retrieve()
                    .onStatus(status -> status.value() == 401,
                            (req, res) -> {
                                throw new SmsGatewayException(
                                        SmsGatewayException.ErrorType.AUTHENTICATION_FAILED,
                                        "供应商鉴权失败", null);
                            })
                    .onStatus(status -> status.value() == 429,
                            (req, res) -> {
                                throw new SmsGatewayException(
                                        SmsGatewayException.ErrorType.RATE_LIMITED,
                                        "供应商触发限流", null);
                            })
                    .onStatus(HttpStatusCode::is5xxServerError,
                            (req, res) -> {
                                throw new SmsGatewayException(
                                        SmsGatewayException.ErrorType.REMOTE_ERROR,
                                        "供应商服务异常", null);
                            })
                    .body(VendorResponse.class);

            if (response == null || response.requestId() == null) {
                throw new SmsGatewayException(
                        SmsGatewayException.ErrorType.REMOTE_ERROR,
                        "供应商返回缺少 requestId", null);
            }
            SmsResult.Status status = "ACCEPTED".equals(response.code())
                    ? SmsResult.Status.ACCEPTED
                    : SmsResult.Status.REJECTED;
            return new SmsResult(response.requestId(), status);
        } catch (SmsGatewayException ex) {
            throw ex;
        } catch (RestClientException ex) {
            Throwable root = ex.getRootCause();
            SmsGatewayException.ErrorType type = root instanceof SocketTimeoutException
                    ? SmsGatewayException.ErrorType.TIMEOUT
                    : SmsGatewayException.ErrorType.REMOTE_ERROR;
            throw new SmsGatewayException(type, "调用供应商接口失败", ex);
        }
    }

    private record VendorRequest(String phone_number, String template_id, String text) {
    }

    private record VendorResponse(String requestId, String code) {
    }
}

这是可集成代码,依赖 Spring Boot 3 项目中的 spring-boot-starter-web。供应商字段和路径应按真实文档调整,不要把供应商 DTO 暴露到业务包。

注册实现并验证业务解耦

配置类负责选择当前供应商。以后切换供应商时,只需替换 SmsGateway Bean,调用方仍保持不变。

java
package com.example.integration.sms;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;

@Configuration
class SmsIntegrationConfiguration {
    @Bean
    SmsGateway smsGateway(
            RestClient.Builder builder,
            @Value("${vendor-a.base-url}") String baseUrl,
            @Value("${vendor-a.token}") String token) {
        return new VendorASmsAdapter(builder, baseUrl, token);
    }
}

对应配置如下,令牌应由环境变量或密钥管理系统注入,不要提交到代码仓库。

yaml
vendor-a:
  base-url: https://api.vendor-a.example
  token: ${VENDOR_A_TOKEN}

可用模拟服务器返回固定响应后调用 SmsGateway#send 验证。假设供应商返回 200 和 {"requestId":"req-1001","code":"ACCEPTED"},预期结果为:

text
SmsResult[requestId=req-1001, status=ACCEPTED]

实际请求编号会不同;若收到 401、429 或 5xx,业务层应分别得到统一的鉴权失败、限流或远程服务异常,而不是供应商原始错误结构。

设计边界与常见错误

不要在业务服务中直接拼接供应商 JSON,也不要让控制器根据供应商名称写 if-else。这会使鉴权、错误处理和字段转换散落在多个位置,切换供应商时难以完整修改。

统一异常不等于吞掉上下文。日志中应保留供应商名称、远程请求编号和耗时,但不得记录密钥、令牌、完整手机号等敏感数据。重试只适用于超时、连接失败和部分 5xx;鉴权失败、参数错误和明确拒绝通常不应自动重试。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

封装第三方接口适配器

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通