MockMvcFeignContext.java
2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.hotent.feign.mockmvc;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.hotent.feign.mockmvc.client.MockMvcClient;
import org.springframework.cloud.openfeign.FeignContext;
import feign.Client;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
public class MockMvcFeignContext extends FeignContext {
private final MockMvcFeignObjectWrapper mockMvcFeignObjectWrapper;
private final FeignContext delegate;
public MockMvcFeignContext(MockMvcFeignObjectWrapper mockMvcFeignObjectWrapper, FeignContext delegate) {
this.mockMvcFeignObjectWrapper = mockMvcFeignObjectWrapper;
this.delegate = delegate;
}
/**
* 指定的feignclient 使用mockmvc进行转发,其他的feignclient使用http的方式转发
* @param name
* @param type
* @return
* @param <T>
*/
@SuppressWarnings("unchecked")
@Override
public <T> T getInstance(String name, Class<T> type) {
T object = this.delegate.getInstance(name, type);
if (object instanceof Client) {
if(mockmvcContextId(name)){
return (T) object;
}
if(object instanceof MockMvcClient){
MockMvcClient mockMvcClient = (MockMvcClient) object;
return (T) mockMvcClient.getDelegate();
}
}
return (T) this.mockMvcFeignObjectWrapper.wrap(object);
}
private boolean mockmvcContextId(String name){
// 可以指定哪些feignClient 使用MockMvcClient进行转发。
List<String> mockmvcContextIdList = mockMvcFeignObjectWrapper.getApplicationContext().getEnvironment().getProperty("feign.mockmvcclient",List.class);
return matchContextId(name, mockmvcContextIdList);
}
/**
* 匹配contextId, 匹配上的 需要进行mock方式转发feign请求
* @param name
* @param mockmvcContextIdList
* @return
*/
private static boolean matchContextId(String name, List<String> mockmvcContextIdList) {
if(CollectionUtils.isEmpty(mockmvcContextIdList)) {
return false;
}
AntPathMatcher antPathMatcher = new AntPathMatcher();
// 支持antPathMatcher方式配置
for (String contextId : mockmvcContextIdList) {
if(antPathMatcher.match(contextId, name)){
return true;
}
}
return false;
}
@SuppressWarnings("unchecked")
@Override
public <T> Map<String, T> getInstances(String name, Class<T> type) {
Map<String, T> instances = this.delegate.getInstances(name, type);
if (instances == null) {
return null;
}
Map<String, T> convertedInstances = new HashMap<>();
for (Map.Entry<String, T> entry : instances.entrySet()) {
if (entry.getValue() instanceof Client) {
convertedInstances.put(entry.getKey(), entry.getValue());
} else {
convertedInstances.put(entry.getKey(), (T) this.mockMvcFeignObjectWrapper.wrap(entry.getValue()));
}
}
return convertedInstances;
}
}