使用eureka的元數據信息,再配上ribbon的路由功能,就能夠在api-gateway實現不少功能,好比灰度測試、生產調試等等。下面介紹一下,怎麼使用jmnarloch大神提供的ribbon-discovery-filter-spring-cloud-starter,利用簡單的幾行代碼搞定這一切。spring
<dependency> <groupId>io.jmnarloch</groupId> <artifactId>ribbon-discovery-filter-spring-cloud-starter</artifactId> <version>2.1.0</version> </dependency>
eureka: instance: metadataMap: tag: pre-prod
@Component public class DynamicRoutesFilter extends ZuulFilter { private static final Logger LOGGER = LoggerFactory.getLogger(DynamicRoutesFilter.class); @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext requestContext = RequestContext.getCurrentContext(); HttpServletRequest request = requestContext.getRequest(); String tag = request.getHeader("tag"); if(tag != null){ RibbonFilterContextHolder.getCurrentContext().add("tag", tag); } return null; } }
根據請求的tag,路由到標記有指定tag值的服務。注意,若是請求不指定tag,則代碼須要判空一下,另外不指定tag的話,則默認全部同名的服務都會被路由到。api
想獲取最新資訊,請關注微信公衆號maven