zuul 网关实现自定义路由如下:
zuul 网关的默认SimpleRouteLocator 如果我们需要自定义路由最好重写其中的 getMatchingRoute()方法
例如每次传进来的url总是一样的 但是我们参数中有一个必传参数 apiname,然后我们数据库中又维护了apiname对应的请求的具体地址,那么我们就可以来根据这个实现自定义路由
代码如下:
public class CustomRouteLocator extends SimpleRouteLocator { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private AuthServiceService authServiceService; public CustomRouteLocator(String servletPath, ZuulProperties properties) { super(servletPath, properties); } @Override public Route getMatchingRoute(final String path) { logger.info("Invoking CustomRouteLocator getMatchingRoute method."); RequestContext currentContext = RequestContext.getCurrentContext(); HttpServletRequest request = currentContext.getRequest(); String apiName = OpenApiUtils.getWrapperApiName(request); Route route = authServiceService.getRouteByServiceId(apiName); if (Objects.isNull(route)) { logger.warn("basis apiName can not find matcher route info,apiName is {}", apiName); RouteNotFoundException.build(ROUTE_NOT_FOUND_ERROR.msg(), ROUTE_NOT_FOUND_ERROR.code()); } logger.info("uri is {}, location is {}, apiName is {}.", route.getPath(), route.getLocation(), apiName); return route; } }
然后创建它的bean
@Configuration public class CustomZuulConfig { @Resource protected ZuulProperties zuulProperties; @Bean public CustomRouteLocator dbRouteLocator(DispatcherServletPath server) { return new CustomRouteLocator(server.getPrefix(), zuulProperties); } }
最终还是这个Route 决定 到底路由去哪里