|
| 1 | +package com.alibabcloud.mse.demo; |
| 2 | + |
| 3 | +import io.opentelemetry.api.baggage.Baggage; |
| 4 | +import io.opentelemetry.context.Context; |
| 5 | +import io.opentelemetry.context.Scope; |
| 6 | +import org.slf4j.Logger; |
| 7 | +import org.slf4j.LoggerFactory; |
| 8 | +import org.springframework.cloud.gateway.filter.GatewayFilterChain; |
| 9 | +import org.springframework.cloud.gateway.filter.GlobalFilter; |
| 10 | +import org.springframework.core.Ordered; |
| 11 | +import org.springframework.stereotype.Component; |
| 12 | +import org.springframework.util.MultiValueMap; |
| 13 | +import org.springframework.web.server.ServerWebExchange; |
| 14 | +import reactor.core.publisher.Mono; |
| 15 | + |
| 16 | +@Component |
| 17 | +public class GrayGatewayFilter implements GlobalFilter, Ordered { |
| 18 | + private static final Logger log = LoggerFactory.getLogger(GrayGatewayFilter.class); |
| 19 | + |
| 20 | + @Override |
| 21 | + public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { |
| 22 | + MultiValueMap<String, String> params = exchange.getRequest().getQueryParams(); |
| 23 | + Scope baggageScope = null; |
| 24 | + try { |
| 25 | + if ("12345".equals(params.getFirst("userId"))) { |
| 26 | + String tag = "gray"; |
| 27 | + // 标记流量标签 |
| 28 | + // key固定为__microservice_tag__ |
| 29 | + // value为合法json,同时tag为流量的标签结果 |
| 30 | + Baggage baggage = Baggage.builder() |
| 31 | + .put("__microservice_tag__", "[{\"name\":\"" + tag + "\"}]") |
| 32 | + .build(); |
| 33 | + log.info("request with userId: {}, tagged {}", params.getFirst("userId"), tag); |
| 34 | + baggageScope = baggage.storeInContext(Context.current()).makeCurrent(); |
| 35 | + } |
| 36 | + return chain.filter(exchange); |
| 37 | + } finally { |
| 38 | + if (baggageScope != null) { |
| 39 | + baggageScope.close(); |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * 由于正常的业务请求处理也是一个Filter,所以这儿要确保顺序在业务Filter之前 |
| 46 | + * @return |
| 47 | + */ |
| 48 | + @Override |
| 49 | + public int getOrder() { |
| 50 | + return -1; |
| 51 | + } |
| 52 | +} |
| 53 | + |
0 commit comments