开发者学堂课程【精通 Spring Cloud Alibaba:代码实现创建动态网关实现】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/634/detail/10122
代码实现创建动态网关实现
目录:
一、核心代码
二、相关代码
一、核心代码
@RestController
public class GatewayController {
@Autowired
private GatewayService gatewayService;
/**
*同步网关配置
*
*@return
*/
@RequestMapping("/synGatewayConfig")
public String synGatewayConfig()( return gatewayService.loadRoute();
}}
二、相关代码
@Service
public class GatewayService implements ApplicationEventPublisherAware {
private ApplicationEventPublisher publisher;
@Autowired
Private RouteDefinitionwriter routeDenfinitionWriter;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisherapplicationEventPublisher) {
this.publisher = applicationEventPublisher;}
public String loadRoute() {
RouteDefinition definition = new RouteDefinition();
Map<String, String>predicateParams = new HashMap<>( initialCapacity:8);
PredicateDefinition predicate =new PredicateDefinition();
FilterDefinition filterDefinition = new FilterDefinition();
Map<String, String> filterParams= new HashMap<>( initialCapacity:8);
//如果配置路由 type 为0的话 则从注册中心获取服务
URI uri ==UriComponentsBuilder.fromUriString("1b://"+ gateWayEntity.getRouteUr1()+ "/").b
//定义的路由唯一的 id
definition.setId("member");
predicate.setName("Path");
//路由转发地址
predicateParams.put("pattern","/member/**");
predicate.setArgs(predicateParams);
// 名称是固定的,路径去前缀
filterDefinition.setName("StripPrefix");
filterParams.put("_genkey_0"
,"1");
filterDefinition.setArgs(filterParams);
definition.setPredicates(Arrays.asList(predicate));
definition.setFilters(Arrays.asList(filterDefinition));
definition.setUri(uri);
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
@override
public void setApplicationEventPublisher(ApplicationEventPublisherapplicationEventPublisher){
this.publisher = applicationEventPublisher;
}
public String loadRoute(){
RouteDefinition definition = new RouteDefinition();
Map<String,String>predicateParams=newHashMap<>( initialCapacity:8);
PredicateDefinition predicate = new PredicateDefinition();
FilterDefinition filterDefinition = new FilterDefinition();
Map<String,String> filterParams = new HashMap<>(initialCapacity:8);
//如果配置路由 type 为0的话 则从注册中心获取服务
URI uri = UriComponentsBuilder.fromUriString("lb://mayikt-member/").build().toUri();
// 定义的路由唯一的 id
definition.setId("member");
predicate.setName("Path");
//路由转发地址
predicateParams.put("pattern","/member/**");
predicate.setArgs(predicateParams);}