开发者学堂课程【精通 Spring Cloud Alibaba:代码完全实现动态服务网关】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/634/detail/10123
代码完全实现动态服务网关
代码如下:
@Service
public class GatewayService implements ApplicationEventPublisherAware{
private ApplicationEventPublisher publisher;
@Autowired
private RouteDefinitionWriter routeDefinitionWriter;
@Autowired
private MayiktGatewayMapper mayiktGatewayMapper;
@override
publicvoid setApplicationEventPublisher(ApplicationEventPublisher
applicationEventPublisthis.publisher= applicationEventPublisher; }
public String loadAIILoadRoute()
List<GateWayEntity> gateWayEntities= mayiktGatewayMapper.gateWayAII();
for(GateWayEntity gb:
gateWayEntities) {
loadRoute(gb);}
return “success”;
}
public String loadRoute(GateWayEntity gateWayEntity) {
RouteDefinition definition= newRouteDefinition();
Map<String, String> predicateParams = new HashMap<>( initialCapacity:8);
PredicateDefinition predicate = new PredicateDefinition();
FilterDefinition filterDefinition = new FilterDefinition();
Map<String,String>filterParams= newHashMap<>(initialCapacity: 8);
URI uri = null;
if ("0".equals(gateWayEntity.getRouteType()))
//如果配置路由 type 为0的话 则从注册中心获取服务地址
uri = UriComponentsBuilder.fromUriString("1b://"+ gateWayEntity.getRouteUr1()+"/").build(
} else {
uri=UriComponentsBuilder.fromHttpUrl(gateWayEntity.getRouteUr1()).build().touri();}
//定义的路由唯一的 id
definition.setId(gateWayEntity.getRouteId(OD;
predicate.setName("Path");
//路由转发地址
predicateParams.put("pattern",gateWayEntity.getRoutePattern();
predicate.setArgs(predicateParams);
//名称是固定的, 路径去前缀
filterDefinition.setName("StripPrefix");
filterParams.put("_genkey_0","1");
filterDefinition.setArgs(filterParams);
definition.setPredicates(Arrays.asList(predicate));
definition.setFilters(ArCall to 'asLits with one argument more... (Ctrl+F1)));
definition.setUri(uri);
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
this.publisher.publishEvent(new RefreshRoutesEvent( source: this)); return "success";
}