架構(gòu)圖
配置
api 網(wǎng)關(guān)
主要依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>2.2.3.RELEASE</version>
</dependency>
自定義局部過濾器
public class ABGatewayFilterFactory extends AbstractGatewayFilterFactory<ABGatewayFilterFactory.Config>{
//必須將配置類傳遞給超類
public ABGatewayFilterFactory(){
super(Config.class);
}
- 類名必須是xxGatewayFilterFactory,其中xx用于配置
- 必須注冊為bean
- 必須在構(gòu)造方法中將配置參數(shù)類型傳遞給父類
- 必須顯示聲明配置參數(shù)的順序,實現(xiàn)shortcutFieldOrder()
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList("hosts","weights");
}
- 必須實現(xiàn)public GatewayFilter apply(Config config)方法
灰度發(fā)布局部過濾器實現(xiàn)
@Component
@Slf4j
public class ABGatewayFilterFactory extends AbstractGatewayFilterFactory<ABGatewayFilterFactory.Config>{
//必須將配置類傳遞給超類
public ABGatewayFilterFactory(){
super(Config.class);
}
@Override
public GatewayFilter apply(Config config) {
return new ABGatewayFilter(config);
}
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList("hosts","weights");
}
/**
* 客戶端鏈接過濾器
*/
private static class ABGatewayFilter implements GatewayFilter, Ordered{
private List<Map.Entry<String, Integer>> list;
private Map<String, Integer> weight;
public ABGatewayFilter(Config config){
String[] hosts = config.getHosts().split("[|]");
String[] weights = config.getWeights().split("[|]");
this.weight = new HashMap<>();
for (int i = 0; i < hosts.length; i++) {
weight.put(hosts[i].trim(),Integer.parseInt(weights[i].trim()));
}
if (weight.values().stream().mapToInt(e -> e).sum() != 100) {
//這里不能用浮點數(shù),浮點數(shù)不是精確計算
throw new RuntimeException("權(quán)重分布有誤,所有權(quán)重總和應該為100");
}
//排序
this.list = weight.entrySet().stream()
.sorted((a, b) -> a.getValue() - b.getValue())
.collect(Collectors.toList());
//分段
for (int i = 0; i < this.list.size() -1; i++) {
int sum = 0;
for (int j = 0; j < i; j++) {
sum += this.list.get(j).getValue();
}
this.list.get(i).setValue(this.list.get(i).getValue() + sum);
}
}
@SneakyThrows
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String host = getHost();
ServerHttpRequest request = exchange.getRequest();
URI uri = request.getURI();
addOriginalRequestUrl(exchange, uri);
URI newUri = URI.create(host + uri.getRawPath());
ServerHttpRequest newRequest = request.mutate().uri(newUri).build();
Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
//動態(tài)設(shè)置路由,選擇服務器
Route newRout = Route.async()
.asyncPredicate(route.getPredicate())
.id(route.getId())
.order(route.getOrder())
.uri(newUri)
.build();
exchange.getAttributes().put(GATEWAY_ROUTE_ATTR,newRout);
return chain.filter(exchange.mutate().request(newRequest).build());
}
private String getHost() {
int random = (int) (100 * Math.random());
for (int i = 0; i < list.size() - 1; i++) {
if (list.get(i).getValue() > random) {
return list.get(i).getKey();
}
}
return list.get(list.size() - 1).getKey();
}
public static void addOriginalRequestUrl(ServerWebExchange exchange, URI url) {
exchange.getAttributes().computeIfAbsent(GATEWAY_ORIGINAL_REQUEST_URL_ATTR,
s -> new LinkedHashSet<>());
LinkedHashSet<URI> uris = exchange
.getRequiredAttribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
uris.add(url);
}
@Override
public int getOrder() {
return 999;
}
}
/**
* - AB=http://localhost:11057|http://localhost:11058|http://localhost:11059,1|10|89
*/
@Data
public static class Config{
private String hosts;
private String weights;
}
}
靜態(tài)配置灰度路由
routes:
- id: gray
#目標服務器
uri: http://localhost:11600
predicates:
- Header=gray,true
filters:
#裁剪一級目錄前綴
# - StripPrefix=1
#灰度過濾器
- AB=http://192.168.3.174:8888|http://192.168.3.174:8889,30|70
動態(tài)配置路由服務
@Service
public class DynamicRouteService implements ApplicationEventPublisherAware {
@Resource
private InMemoryRouteDefinitionRepository routeDefinitionWriter;
private ApplicationEventPublisher publisher;
private void notifyChanged() {
this.publisher.publishEvent(new RefreshRoutesEvent(this));
}
/**
* 獲取路由列表
* @return
*/
public Flux<RouteDefinition> list(){
return routeDefinitionWriter.getRouteDefinitions();
}
/**
* 增加路由
*
*/
public String add(RouteDefinition definition) {
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
notifyChanged();
return "success";
}
/**
* 更新路由
*/
public String update(RouteDefinition definition) {
try {
this.routeDefinitionWriter.delete(Mono.just(definition.getId()));
} catch (Exception e) {
return "update fail,not find route routeId: " + definition.getId();
}
try {
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
notifyChanged();
return "success";
} catch (Exception e) {
return "update route fail";
}
}
/**
* 刪除路由
*
*/
public String delete(String id) {
try {
this.routeDefinitionWriter.delete(Mono.just(id)).subscribe();
notifyChanged();
return "delete success";
} catch (Exception e) {
e.printStackTrace();
return "delete fail";
}
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
}
注意:動態(tài)配置路由存在于InMemoryRouteDefinitionRepository中,不影響靜態(tài)配置的路由
全局過濾器示例
@Component
@Slf4j
public class SimpleGlobalFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("全局過濾器 filter");
return chain.filter( exchange );
}
@Override
public int getOrder() {
return 0;
}
}