? 背景與需求
需要基于 OkHttp?框架封裝一個 HTTP 客戶端,用于調用外部服務接口(如拼團回調),實現以下功能:
- 動態傳入請求地址(URL)
- 支持 JSON 請求體
- 實現類放在 infrastructure?層的 gateway?包下
- 接口定義在 domain?層,實現類為 GroupBuyNotifyService
? 項目結構參考
group-buy-market
├── group-buy-market-domain
│ ??└── src/main/java/cn/bugstack/domain/trade/service/settlement/notify/GroupBuyNotifyService.java
├── group-buy-market-infrastructure
│ ??└── src/main/java/cn/bugstack/infrastructure/gateway/GroupBuyNotifyGateway.java
?接口設計
1. 領域層接口(定義在 domain)
// GroupBuyNotifyService.java
package cn.bugstack.domain.trade.service.settlement.notify;import cn.bugstack.domain.trade.model.entity.NotifyTaskEntity;import java.util.Map;public interface GroupBuyNotifyService {String groupBuyNotify(NotifyTaskEntity notifyTaskEntity);
}
2. 基礎設施層實現(定義在 infrastructure)
// GroupBuyNotifyGateway.java
package cn.bugstack.infrastructure.gateway;import cn.bugstack.domain.trade.model.entity.NotifyTaskEntity;
import cn.bugstack.domain.trade.service.settlement.notify.GroupBuyNotifyService;
import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.springframework.stereotype.Service;import java.io.IOException;@Service
public class GroupBuyNotifyGateway implements GroupBuyNotifyService {private final final OkHttpClient httpClient;public GroupBuyNotifyGateway(OKHttpClientConfig okHttpClientConfig) {this.httpClient = okHttpClientConfig.getOkHttpClient();}@Overridepublic String groupBuyNotify(NotifyTaskEntity notifyTaskEntity) {String url = notifyTaskEntity.getNotifyUrl(); // 動態 URLString requestBody = JSON.toJSONString(notifyTaskEntity); // 請求體Request request = new Request.Builder().url(url).post(RequestBody.create(requestBody, MediaType.get("application/json; charset=utf-8"))).build();try (Response response = httpClient.newCall(request).execute()) {if (response.isSuccessful() && response.body() != null) {return response.body().string();} else {return "HTTP_ERROR";}} catch (IOException e) {e.printStackTrace();return "NETWORK_ERROR";}}
}
? 配置類(OkHttpClient 配置)
// OKHttpClientConfig.java
package cn.bugstack.infrastructure.config;import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.time.Duration;@Configuration
public class OKHttpClientConfig {@Beanpublic OkHttpClient okHttpClient() {return new OkHttpClient.Builder().connectTimeout(Duration.ofSeconds(10)).readTimeout(Duration.ofSeconds(30)).writeTimeout(Duration.ofSeconds(30)).build();}public OkHttpClient getOkHttpClient() {return okHttpClient();}
}
? 總結功能
功能 | 實現方式 |
動態 URL | 從 notifyTaskEntity.getNotifyUrl()?獲取 |
請求體 | 使用 FastJSON?序列化 NotifyTaskEntity |
HTTP 客戶端 | 使用 OkHttpClient?發送 POST 請求 |
異常處理 | 捕獲 IO 異常并返回錯誤碼 |
分層結構 | 接口在 domain,實現類在 infrastructure/gateway |