org.springframework.cloud.gateway.route.RouteDefinition Java Examples
The following examples show how to use
org.springframework.cloud.gateway.route.RouteDefinition.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DynamicRouteServiceImplByNacos.java From spring-cloud-gateway-nacos with Apache License 2.0 | 6 votes |
/** * 监听Nacos Server下发的动态路由配置 * @param dataId * @param group */ public void dynamicRouteByNacosListener (String dataId, String group){ try { ConfigService configService=NacosFactory.createConfigService("127.0.0.1:8848"); String content = configService.getConfig(dataId, group, 5000); System.out.println(content); configService.addListener(dataId, group, new Listener() { @Override public void receiveConfigInfo(String configInfo) { RouteDefinition definition= JSON.parseObject(configInfo,RouteDefinition.class); dynamicRouteService.update(definition); } @Override public Executor getExecutor() { return null; } }); } catch (NacosException e) { //todo 提醒:异常自行处理此处省略 } }
Example #2
Source File: RouteController.java From spring-cloud-gateway-nacos with Apache License 2.0 | 6 votes |
private RouteDefinition assembleRouteDefinition(GatewayRouteDefinition gwdefinition) { RouteDefinition definition = new RouteDefinition(); List<PredicateDefinition> pdList=new ArrayList<>(); definition.setId(gwdefinition.getId()); List<GatewayPredicateDefinition> gatewayPredicateDefinitionList=gwdefinition.getPredicates(); for (GatewayPredicateDefinition gpDefinition: gatewayPredicateDefinitionList) { PredicateDefinition predicate = new PredicateDefinition(); predicate.setArgs(gpDefinition.getArgs()); predicate.setName(gpDefinition.getName()); pdList.add(predicate); } definition.setPredicates(pdList); URI uri = UriComponentsBuilder.fromHttpUrl(gwdefinition.getUri()).build().toUri(); definition.setUri(uri); return definition; }
Example #3
Source File: GatewayControllerEndpointTests.java From spring-cloud-gateway with Apache License 2.0 | 6 votes |
@Test public void testPostRouteWithNotExistingPredicate() { RouteDefinition testRouteDefinition = new RouteDefinition(); testRouteDefinition.setUri(URI.create("http://example.org")); PredicateDefinition predicateDefinition = new PredicateDefinition( "NotExistingPredicate=test-config"); testRouteDefinition.setPredicates(Collections.singletonList(predicateDefinition)); testClient.post() .uri("http://localhost:" + port + "/actuator/gateway/routes/test-route") .accept(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(testRouteDefinition)).exchange() .expectStatus().isBadRequest(); }
Example #4
Source File: GatewayControllerEndpointTests.java From spring-cloud-gateway with Apache License 2.0 | 6 votes |
@Test public void testPostRouteWithNotExistingFilter() { RouteDefinition testRouteDefinition = new RouteDefinition(); testRouteDefinition.setUri(URI.create("http://example.org")); FilterDefinition filterDefinition = new FilterDefinition( "NotExistingFilter=test-config"); testRouteDefinition.setFilters(Collections.singletonList(filterDefinition)); testClient.post() .uri("http://localhost:" + port + "/actuator/gateway/routes/test-route") .accept(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(testRouteDefinition)).exchange() .expectStatus().isBadRequest(); }
Example #5
Source File: JeecgRouteDefinitionRepository.java From jeecg-cloud with Apache License 2.0 | 6 votes |
@Override public Flux<RouteDefinition> getRouteDefinitions() { log.info("---进入动态路由加载---"); try { Object str = redisTemplate.opsForValue().get(GATEWAY_ROUTES); if(str==null || str.toString().equals("")){ log.info("无路由配置"); }else{ log.info(str.toString()); JSONArray array = JSON.parseArray(str.toString()); List<RouteDefinition> ls = GatewayUtils.getRoutesByJson(array); return Flux.fromIterable(ls); } } catch (Exception e) { log.info("GatewayUtils.getRoutesByJson 出错!"); e.printStackTrace(); } return Flux.fromIterable(new ArrayList<>()); }
Example #6
Source File: DynamicRouteService.java From momo-cloud-permission with Apache License 2.0 | 6 votes |
@Override public Flux<RouteDefinition> getRouteDefinitions() { //TODO 将redis改为 本地 map,用mq/配置中心更新map List<RouteDefinition> allRouteDefinitions = new ArrayList<>(); // if (CollectionUtils.isEmpty(routeMap)) { // //获取配置文件中的路由参数 // List<RouteDefinition> routeDefinitions = properties.getRoutes(); // routeDefinitions.forEach(routeDefinition -> { // DynamicRouteMap.put(routeDefinition.getId(), routeDefinition); // }); // allRouteDefinitions.addAll(routeDefinitions); // } else { routeMap.forEach((k, v) -> { allRouteDefinitions.add(v); }); // } // log.info("路由信息为:{}", JSONObject.toJSONString(allRouteDefinitions)); return Flux.fromIterable(allRouteDefinitions); }
Example #7
Source File: DynamicRouteConfigurationService.java From wecube-platform with Apache License 2.0 | 6 votes |
public List<RouteItemInfoDto> listAllContextRouteItems() { Flux<RouteDefinition> flux = routeDefinitionRepository.getRouteDefinitions(); List<RouteItemInfoDto> items = new ArrayList<>(); flux.subscribe((rd) -> { RouteItemInfoDto r = new RouteItemInfoDto(); r.setContext(rd.getId()); String uri = rd.getUri().toString(); String scheme = uri.substring(0, uri.indexOf("://")); uri = uri.substring(uri.indexOf("://") + 3); String host = uri.substring(0, uri.indexOf(":")); String port = uri.substring(uri.indexOf(":") + 1); r.setHost(host); r.setPort(port); r.setHttpScheme(scheme); items.add(r); }); return items; }
Example #8
Source File: AbstractGatewayControllerEndpoint.java From spring-cloud-gateway with Apache License 2.0 | 6 votes |
@PostMapping("/routes/{id}") @SuppressWarnings("unchecked") public Mono<ResponseEntity<Object>> save(@PathVariable String id, @RequestBody RouteDefinition route) { return Mono.just(route).filter(this::validateRouteDefinition) .flatMap(routeDefinition -> this.routeDefinitionWriter .save(Mono.just(routeDefinition).map(r -> { r.setId(id); log.debug("Saving route: " + route); return r; })) .then(Mono.defer(() -> Mono.just(ResponseEntity .created(URI.create("/routes/" + id)).build())))) .switchIfEmpty( Mono.defer(() -> Mono.just(ResponseEntity.badRequest().build()))); }
Example #9
Source File: RouteService.java From SpringCloud with Apache License 2.0 | 6 votes |
@PostConstruct private void loadRouteDefinition() { log.info("loadRouteDefinition, 开始初使化路由"); Set<String> gatewayKeys = stringRedisTemplate.keys(GATEWAY_ROUTES + "*"); if (CollectionUtils.isEmpty(gatewayKeys)) { return; } log.info("预计初使化路由, gatewayKeys:{}", gatewayKeys); // 去掉key的前缀 Set<String> gatewayKeyIds = gatewayKeys.stream().map(key -> { return key.replace(GATEWAY_ROUTES, StringUtils.EMPTY); }).collect(Collectors.toSet()); Map<String, RouteDefinition> allRoutes = gatewayRouteCache.getAll(gatewayKeyIds); log.info("gatewayKeys:{}", allRoutes); // 以下代码原因是,jetcache将RouteDefinition返序列化后,uri发生变化,未初使化,导致路由异常,以下代码是重新初使化uri allRoutes.values().forEach(routeDefinition -> { try { routeDefinition.setUri(new URI(routeDefinition.getUri().toASCIIString())); } catch (URISyntaxException e) { log.error("网关加载RouteDefinition异常:", e); } }); routeDefinitionMaps.putAll(allRoutes); log.info("共初使化路由信息:{}", routeDefinitionMaps.size()); }
Example #10
Source File: GatewayRouteService.java From SpringCloud with Apache License 2.0 | 6 votes |
/** * 将数据库中json对象转换为网关需要的RouteDefinition对象 * * @param gatewayRoute * @return RouteDefinition */ private RouteDefinition gatewayRouteToRouteDefinition(GatewayRoute gatewayRoute) { RouteDefinition routeDefinition = new RouteDefinition(); routeDefinition.setId(gatewayRoute.getRouteId()); routeDefinition.setOrder(gatewayRoute.getOrders()); routeDefinition.setUri(URI.create(gatewayRoute.getUri())); ObjectMapper objectMapper = new ObjectMapper(); try { routeDefinition.setFilters(objectMapper.readValue(gatewayRoute.getFilters(), new TypeReference<List<FilterDefinition>>() { })); routeDefinition.setPredicates(objectMapper.readValue(gatewayRoute.getPredicates(), new TypeReference<List<PredicateDefinition>>() { })); } catch (IOException e) { log.error("网关路由对象转换失败", e); } return routeDefinition; }
Example #11
Source File: AbstractGatewayControllerEndpoint.java From spring-cloud-gateway with Apache License 2.0 | 5 votes |
private boolean validateRouteDefinition(RouteDefinition routeDefinition) { boolean hasValidFilterDefinitions = routeDefinition.getFilters().stream() .allMatch(filterDefinition -> GatewayFilters.stream() .anyMatch(gatewayFilterFactory -> filterDefinition.getName() .equals(gatewayFilterFactory.name()))); boolean hasValidPredicateDefinitions = routeDefinition.getPredicates().stream() .allMatch(predicateDefinition -> routePredicates.stream() .anyMatch(routePredicate -> predicateDefinition.getName() .equals(routePredicate.name()))); log.debug("FilterDefinitions valid: " + hasValidFilterDefinitions); log.debug("PredicateDefinitions valid: " + hasValidPredicateDefinitions); return hasValidFilterDefinitions && hasValidPredicateDefinitions; }
Example #12
Source File: DynamicRouteServiceImpl.java From spring-cloud-gateway-nacos with Apache License 2.0 | 5 votes |
/** * spring: cloud: gateway: routes: #当访问http://localhost:8080/baidu,直接转发到https://www.baidu.com/ - id: baidu_route uri: http://baidu.com:80/ predicates: - Path=/baidu * @param args */ public static void main(String[] args) { GatewayRouteDefinition definition = new GatewayRouteDefinition(); GatewayPredicateDefinition predicate = new GatewayPredicateDefinition(); Map<String, String> predicateParams = new HashMap<>(8); definition.setId("jd_route"); predicate.setName("Path"); predicateParams.put("pattern", "/jd"); predicate.setArgs(predicateParams); definition.setPredicates(Arrays.asList(predicate)); String uri="http://www.jd.com"; //URI uri = UriComponentsBuilder.fromHttpUrl("http://www.baidu.com").build().toUri(); definition.setUri(uri); System.out.println("definition:"+JSON.toJSONString(definition)); RouteDefinition definition1 = new RouteDefinition(); PredicateDefinition predicate1 = new PredicateDefinition(); Map<String, String> predicateParams1 = new HashMap<>(8); definition1.setId("baidu_route"); predicate1.setName("Path"); predicateParams1.put("pattern", "/baidu"); predicate1.setArgs(predicateParams1); definition1.setPredicates(Arrays.asList(predicate1)); URI uri1 = UriComponentsBuilder.fromHttpUrl("http://www.baidu.com").build().toUri(); definition1.setUri(uri1); System.out.println("definition1:"+JSON.toJSONString(definition1)); }
Example #13
Source File: NacosRouteDefinitionRepository.java From microservices-platform with Apache License 2.0 | 5 votes |
@Override public Flux<RouteDefinition> getRouteDefinitions() { try { String content = nacosConfigProperties.configServiceInstance().getConfig(SCG_DATA_ID, SCG_GROUP_ID,5000); List<RouteDefinition> routeDefinitions = getListByStr(content); return Flux.fromIterable(routeDefinitions); } catch (NacosException e) { log.error("getRouteDefinitions by nacos error", e); } return Flux.fromIterable(CollUtil.newArrayList()); }
Example #14
Source File: GatewayRouteService.java From SpringCloud with Apache License 2.0 | 5 votes |
@Override public boolean update(GatewayRoute gatewayRoute) { boolean isSuccess = this.updateById(gatewayRoute); // 转化为gateway需要的类型,缓存到redis, 并事件通知各网关应用 RouteDefinition routeDefinition = gatewayRouteToRouteDefinition(gatewayRoute); gatewayRouteCache.put(gatewayRoute.getRouteId(), routeDefinition); eventSender.send(BusConfig.ROUTING_KEY, routeDefinition); return isSuccess; }
Example #15
Source File: RedisRouteDefinitionRepository.java From SpringCloud with Apache License 2.0 | 5 votes |
@Override public Mono<Void> save(Mono<RouteDefinition> route) { return route.flatMap(routeDefinition -> { routeService.save(routeDefinition); return Mono.empty(); }); }
Example #16
Source File: GatewayRouteService.java From SpringCloud with Apache License 2.0 | 5 votes |
@Override public boolean add(GatewayRoute gatewayRoute) { boolean isSuccess = this.save(gatewayRoute); // 转化为gateway需要的类型,缓存到redis, 并事件通知各网关应用 RouteDefinition routeDefinition = gatewayRouteToRouteDefinition(gatewayRoute); gatewayRouteCache.put(gatewayRoute.getRouteId(), routeDefinition); eventSender.send(BusConfig.ROUTING_KEY, routeDefinition); return isSuccess; }
Example #17
Source File: GatewayLegacyControllerEndpoint.java From spring-cloud-gateway with Apache License 2.0 | 5 votes |
@GetMapping("/routes/{id}") public Mono<ResponseEntity<RouteDefinition>> route(@PathVariable String id) { // TODO: missing RouteLocator return this.routeDefinitionLocator.getRouteDefinitions() .filter(route -> route.getId().equals(id)).singleOrEmpty() .map(ResponseEntity::ok) .switchIfEmpty(Mono.just(ResponseEntity.notFound().build())); }
Example #18
Source File: DiscoveryClientRouteDefinitionLocator.java From spring-cloud-gateway with Apache License 2.0 | 5 votes |
protected RouteDefinition buildRouteDefinition(Expression urlExpr, ServiceInstance serviceInstance) { String serviceId = serviceInstance.getServiceId(); RouteDefinition routeDefinition = new RouteDefinition(); routeDefinition.setId(this.routeIdPrefix + serviceId); String uri = urlExpr.getValue(this.evalCtxt, serviceInstance, String.class); routeDefinition.setUri(URI.create(uri)); // add instance metadata routeDefinition.setMetadata(new LinkedHashMap<>(serviceInstance.getMetadata())); return routeDefinition; }
Example #19
Source File: GatewayControllerEndpointTests.java From spring-cloud-gateway with Apache License 2.0 | 5 votes |
@Test public void testPostValidRouteDefinition() { RouteDefinition testRouteDefinition = new RouteDefinition(); testRouteDefinition.setUri(URI.create("http://example.org")); FilterDefinition prefixPathFilterDefinition = new FilterDefinition( "PrefixPath=/test-path"); FilterDefinition redirectToFilterDefinition = new FilterDefinition( "RemoveResponseHeader=Sensitive-Header"); FilterDefinition testFilterDefinition = new FilterDefinition("TestFilter"); testRouteDefinition.setFilters(Arrays.asList(prefixPathFilterDefinition, redirectToFilterDefinition, testFilterDefinition)); PredicateDefinition hostRoutePredicateDefinition = new PredicateDefinition( "Host=myhost.org"); PredicateDefinition methodRoutePredicateDefinition = new PredicateDefinition( "Method=GET"); PredicateDefinition testPredicateDefinition = new PredicateDefinition( "Test=value"); testRouteDefinition.setPredicates(Arrays.asList(hostRoutePredicateDefinition, methodRoutePredicateDefinition, testPredicateDefinition)); testClient.post() .uri("http://localhost:" + port + "/actuator/gateway/routes/test-route") .accept(MediaType.APPLICATION_JSON) .body(BodyInserters.fromValue(testRouteDefinition)).exchange() .expectStatus().isCreated(); }
Example #20
Source File: DiscoveryClientRouteDefinitionLocatorTests.java From spring-cloud-gateway with Apache License 2.0 | 5 votes |
@Test public void includeExpressionWorks() { assertThat(locator).as("DiscoveryClientRouteDefinitionLocator was null") .isNotNull(); List<RouteDefinition> definitions = locator.getRouteDefinitions().collectList() .block(); assertThat(definitions).hasSize(1); RouteDefinition definition = definitions.get(0); assertThat(definition.getId()).isEqualTo("testedge_SERVICE1"); assertThat(definition.getUri()).hasScheme("lb").hasHost("SERVICE1"); assertThat(definition.getMetadata()).containsEntry("edge", "true"); assertThat(definition.getPredicates()).hasSize(1); PredicateDefinition predicate = definition.getPredicates().get(0); assertThat(predicate.getName()).isEqualTo("Path"); assertThat(predicate.getArgs()).hasSize(1).containsEntry(PATTERN_KEY, "/service1/**"); assertThat(definition.getFilters()).hasSize(1); FilterDefinition filter = definition.getFilters().get(0); assertThat(filter.getName()).isEqualTo("RewritePath"); assertThat(filter.getArgs()).hasSize(2) .containsEntry(REGEXP_KEY, "/service1/(?<remaining>.*)") .containsEntry(REPLACEMENT_KEY, "/${remaining}"); }
Example #21
Source File: ReactiveGatewayDiscoveryClientAutoConfigurationTests.java From spring-cloud-gateway with Apache License 2.0 | 5 votes |
@Test public void routeLocatorBeanExists() { assertThat(locator).as("DiscoveryClientRouteDefinitionLocator was null") .isNotNull(); List<RouteDefinition> definitions = locator.getRouteDefinitions() .collectList().block(); assertThat(definitions).hasSize(1); }
Example #22
Source File: RouteController.java From spring-cloud-gateway-nacos with Apache License 2.0 | 5 votes |
/** * 增加路由 * @param gwdefinition * @return */ @PostMapping("/add") public String add(@RequestBody GatewayRouteDefinition gwdefinition) { try { RouteDefinition definition = assembleRouteDefinition(gwdefinition); return this.dynamicRouteService.add(definition); } catch (Exception e) { e.printStackTrace(); } return "succss"; }
Example #23
Source File: DynamicRouteConfigurationService.java From wecube-platform with Apache License 2.0 | 5 votes |
private void refreshAllLoadedContexts() { Flux<RouteDefinition> flux = routeDefinitionRepository.getRouteDefinitions(); flux.subscribe((rd) -> { this.loadedContexts.put(rd.getId(), object); }); }
Example #24
Source File: GatewayUtils.java From jeecg-cloud with Apache License 2.0 | 5 votes |
/** * redis中的信息需要处理下 转成RouteDefinition对象 * - id: login * uri: lb://cloud-jeecg-system * predicates: * - Path=/jeecg-boot/sys/**, * @param array * @return */ public static List<RouteDefinition> getRoutesByJson(JSONArray array) throws URISyntaxException { List<RouteDefinition> ls = new ArrayList<>(); for(int i=0;i<array.size();i++) { JSONObject obj = array.getJSONObject(i); RouteDefinition route = new RouteDefinition(); route.setId(obj.getString("id")); Object uri = obj.get("uri"); if(uri==null){ route.setUri(new URI("lb://"+obj.getString("name"))); }else{ route.setUri(new URI(obj.getString("uri"))); } Object predicates = obj.get("predicates"); if (predicates != null) { JSONArray predicatesArray = JSONArray.parseArray(predicates.toString()); List<PredicateDefinition> predicateDefinitionList = predicatesArray.toJavaList(PredicateDefinition.class); route.setPredicates(predicateDefinitionList); } Object filters = obj.get("filters"); if (filters != null) { JSONArray filtersArray = JSONArray.parseArray(filters.toString()); List<FilterDefinition> filterDefinitionList = filtersArray.toJavaList(FilterDefinition.class); route.setFilters(filterDefinitionList); } ls.add(route); } return ls; }
Example #25
Source File: DynamicRouteService.java From momo-cloud-permission with Apache License 2.0 | 5 votes |
@Override public Mono<Void> save(Mono<RouteDefinition> route) { return route .flatMap(routeDefinition -> { redisTemplate.opsForHash().put(GATEWAY_ROUTES, routeDefinition.getId(), JSON.toJSONString(routeDefinition)); return Mono.empty(); }); }
Example #26
Source File: DynamicRouteService.java From momo-cloud-permission with Apache License 2.0 | 5 votes |
@PostConstruct public void initializeRouteToMap() { //获取配置文件中的路由参数 List<RouteDefinition> routeDefinitions = properties.getRoutes(); routeDefinitions.forEach(routeDefinition -> { routeMap.put(routeDefinition.getId(), routeDefinition); }); }
Example #27
Source File: BusReceiver.java From SpringCloud with Apache License 2.0 | 4 votes |
public void handleMessage(RouteDefinition routeDefinition) { log.info("Received Message:<{}>", routeDefinition); // 待实现动态del路由 routeService.save(routeDefinition); }
Example #28
Source File: NacosRouteDefinitionRepository.java From microservices-platform with Apache License 2.0 | 4 votes |
@Override public Mono<Void> save(Mono<RouteDefinition> route) { return null; }
Example #29
Source File: NacosRouteDefinitionRepository.java From microservices-platform with Apache License 2.0 | 4 votes |
private List<RouteDefinition> getListByStr(String content) { if (StrUtil.isNotEmpty(content)) { return JSONObject.parseArray(content, RouteDefinition.class); } return new ArrayList<>(0); }
Example #30
Source File: JeecgRouteDefinitionRepository.java From jeecg-cloud with Apache License 2.0 | 4 votes |
@Override public Mono<Void> save(Mono<RouteDefinition> route) { return null; }