原創:猿天地(微信公眾號ID:cxytiandi),歡迎分享,轉載請保留出處。
前面我們介紹了在微服務架構下如何解決單測時 Mock 的問題,通過 Mock 可以在單測時不依賴其他服務的實現。在文章最后我也給大家提供了一個思考題:是不是可以模擬前端對后端的處理方式,走 Yapi 的 Mock 功能? 這樣就不用自己手動的對每個接口去 Mock 了。
首先我們需要定義一個 Mock 的配置類,用于配置哪些遠程調用需要進行 Mock。
@Data
@Configuration
@ConfigurationProperties(prefix = "mock")
public class ApiMockProperties {
/**
* 資源:mock地址
* 格式:GET:http://user-provider/user/{userId}##http://xxx.com/mock/api/1001
*/
private List<String> apis;
public String getMockApi(String resource) {
if (CollectionUtils.isEmpty(apis)) {
return null;
}
Map<String, String> apiMap = apis.stream().collect(Collectors.toMap(s -> {
return s.split("##")[0];
}, s -> s.split("##")[1]));
return apiMap.get(resource);
}
}
比如我們的 Feign Client 定義如下:
@FeignClient(name = "kitty-cloud-user-provider")
public interface UserRemoteService {
/**
* 根據用戶ID查詢用戶
* @param userId 用戶ID
* @return
*/
@GetMapping("/users/{userId}")
ResponseData<UserResponse> getUser(@PathVariable("userId") Long userId);
}
那么資源的格式就是 GET:http://kitty-cloud-user-provider/users/{userId},以 2 個#作為分隔符,后面接上 Mock 的地址。
配置格式如下:
mock.apis[0]=GET:http://kitty-cloud-user-provider/users/{userId}##http://yapi.cxytiandi.com/mock/74/v1/user
配置好了后就需要想辦法對 Feign 進行擴展,如果調用的接口在 Mock 配置中,就走 Mock 的地址。
對 Feign 擴展可以參考 Sleuth 中的做法,詳細代碼就不貼了,文末貼上完整源碼參考地址。
新增一個類,繼承 LoadBalancerFeignClient,重寫 execute 方法。需要判斷當前執行的接口是否在 Mock 名單中,如果在就執行 Mock 操作。
public class MockLoadBalancerFeignClient extends LoadBalancerFeignClient {
private ApiMockProperties apiMockProperties;
public MockLoadBalancerFeignClient(Client delegate, CachingSpringLoadBalancerFactory lbClientFactory,
SpringClientFactory clientFactory, ApiMockProperties apiMockProperties) {
super(delegate, lbClientFactory, clientFactory);
this.apiMockProperties = apiMockProperties;
}
@Override
public Response execute(Request request, Request.Options options) throws IOException {
RequestContext currentContext = ContextHolder.getCurrentContext();
String feignCallResourceName = currentContext.get("feignCallResourceName");
String mockApi = apiMockProperties.getMockApi(feignCallResourceName);
if (StringUtils.hasText(feignCallResourceName) && StringUtils.hasText(mockApi)) {
Request newRequest = Request.create(request.httpMethod(),
mockApi, request.headers(), request.requestBody());
return super.getDelegate().execute(newRequest, options);
} else {
return super.execute(request, options);
}
}
}
feignCallResourceName 是通過 ThreadLocal 來傳遞的,如果沒有 Restful 風格的 API 就不用這樣做了,直接判斷 url 即可。
Restful 的需要獲取到原始的 uri 定義才行,不然就是/users/1, /users/2 沒辦法判斷是否在 Mock 名單中。
所以我們得改改底層的代碼,由于項目中用的是 Sentinel 做熔斷,所以在接口調用的時候會先進入 Sentinel 的 SentinelInvocationHandler,我們可以在這個類中進行資源名稱的獲取,然后通過 ThreadLocal 進行透傳。
這樣在 LoadBalancerFeignClient 中就可以獲取資源名然后去 Mock 名單中判斷了。
String resourceName = methodMetadata.template().method().toUpperCase()
+ ":" + hardCodedTarget.url() + methodMetadata.template().path();
RequestContext requestContext = ContextHolder.getCurrentContext();
requestContext.add("feignCallResourceName", resourceName);
Entry entry = null;
try {
ContextUtil.enter(resourceName);
entry = SphU.entry(resourceName, EntryType.OUT, 1, args);
result = methodHandler.invoke(args);
}
核心代碼并不多,當然也省略了如何去替換 LoadBalancerFeignClient 的相關代碼,完整源碼地址如下:https://github.com/yinjihuan/kitty/tree/feature/1.0/kitty-servicecall/kitty-servicecall-feign/src/main/java/com/cxytiandi/kitty/servicecall/feign
關于作者:尹吉歡,簡單的技術愛好者,《Spring Cloud微服務-全棧技術與案例解析》, 《Spring Cloud微服務 入門 實戰與進階》作者, 公眾號 猿天地 發起人。