步骤:
(1)读取zuul的配置文件,获取路由配置项信息;
private static Properties props; static { String fileName = "application.properties"; props = new Properties(); try { props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName), "UTF-8")); } catch (IOException e) { log.error("配置文件读取异常", e); } }
(2)在获取到的配置项信息中截取出服务的路由配置信息;
/** * 根据zuul.routes.KSKZT.serviceId * 获取KSKZT * @param key * @return */ public static String getRoutesKey(String key){ return key.replace("zuul.routes.", "").replace(".serviceId", ""); } /** * 根据KSKZT * 获取zuul.routes.KSKZT.path * @param key * @return */ public static String getRoutesPathKey(String key){ return "zuul.routes."+key+".path"; } /** * 根据zuul.routes.KSKZT.path * 获取/KSKZT/** * @param pathKay * @return */ public static String getRoutesPathPalue(String pathKay){ return props.getProperty(pathKay.trim()); } /** * 获取系统配置的注册名称 * @return */ public static String getApplicationName(){ return props.getProperty("spring.application.name"); } /** * 获取路由表 * @return */ public static List<Map<String,String>> getRouteList(){ List<Map<String,String>> routeList = new ArrayList<>(); for(Object key : props.keySet()){ if(key.toString().startsWith("zuul.routes") && key.toString().endsWith(".serviceId") ){ Map< String, String> route = new HashMap<String, String>(); route.put("serviceName",props.get(key)+""); route.put("servicePath",getApplicationName()+getRoutesPathPalue(getRoutesPathKey(getRoutesKey(key.toString())))); routeList.add(route); } } return routeList; }
测试获取到的路由表
public static void main(String[] args) { List<Map<String,String>> list = getRouteList(); for (Map<String,String> object : list) { System.out.println("********************"); System.out.println(object.get("serviceName")); System.out.println(object.get("servicePath")); } }
(3)保证监控平台获取正确的路由表;
1)在监控平台启动时:通过HttpClient请求zuul提供的接口,获取路由表信息
2)在zuul启动时:通过的HttpClient请求监控平台的更新接口,将路由表作为参数传递给监控平台,监控平台接受并更新。