架构图
配置
api 网关
主要依赖
org.springframework.cloud
spring-cloud-starter-gateway
2.2.3.RELEASE
自定义局部过滤器
public class ABGatewayFilterFactory extends AbstractGatewayFilterFactory{
//必须将配置类传递给超类
public ABGatewayFilterFactory(){
super(Config.class);
}
- 类名必须是xxGatewayFilterFactory,其中xx用于配置
- 必须注册为bean
- 必须在构造方法中将配置参数类型传递给父类
- 必须显示声明配置参数的顺序,实现shortcutFieldOrder()
@Override
public List shortcutFieldOrder() {
return Arrays.asList("hosts","weights");
}
- 必须实现public GatewayFilter apply(Config config)方法
灰度发布局部过滤器实现
@Component
@Slf4j
public class ABGatewayFilterFactory extends AbstractGatewayFilterFactory{
//必须将配置类传递给超类
public ABGatewayFilterFactory(){
super(Config.class);
}
@Override
public GatewayFilter apply(Config config) {
return new ABGatewayFilter(config);
}
@Override
public List shortcutFieldOrder() {
return Arrays.asList("hosts","weights");
}
/**
* 客户端链接过滤器
*/
private static class ABGatewayFilter implements GatewayFilter, Ordered{
private List> list;
private Map 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) {
//这里不能用浮点数,浮点数不是精确计算
throw new RuntimeException("权重分布有误,所有权重总和应该为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 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);
//动态设置路由,选择服务器
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 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;
}
}
静态配置灰度路由
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
动态配置路由服务
@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 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;
}
}
注意:动态配置路由存在于InMemoryRouteDefinitionRepository中,不影响静态配置的路由
全局过滤器示例
@Component
@Slf4j
public class SimpleGlobalFilter implements GlobalFilter, Ordered {
@Override
public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("全局过滤器 filter");
return chain.filter( exchange );
}
@Override
public int getOrder() {
return 0;
}
}