重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
这篇文章给大家分享的是有关SpringCloudGateway开发的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
创新互联长期为千余家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为民丰企业提供专业的成都网站设计、成都网站制作,民丰网站改版等技术服务。拥有10多年丰富建站经验和众多成功案例,为您定制开发。路由简介:
1.SpringCloudGateWay 是用于替代zuul作为API网关,在gateway中有三个重要的名词:过滤器,断言,路由
过滤器与断言是路由的一部分,路由便是将请求进行一系列的处理后分发到各个服务的一个过程。
路由的过程:首先会加载断言以及路由,在接受到请求后根据断言加载的顺序会匹配到先加载的断言,只有与断言匹配了的请求才会进入路由,没有匹配到的服务会将请求当成普通的访问请求。
2:路由加载断言的方式:
断言加载的方式有四种,分别是配置文件,java编码,数据库以及注册中心
第一种配置文件:
在官方文档中主要介绍的就是配置文件的加载方式
官方地址:https://cloud.spring.io/spring-cloud-gateway/reference/html/#gateway-starter
一般的断言有三种要素:id,uri,predicate.
id是断言的标识,uri是ip+端口,predicate则是断言匹配的规则
3:示例:
新建一个springboot项目,并且引入springcloudgateway的依赖
org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-starter-gateway
在启动类注册三个全局过滤器
@SpringBootApplication public class GateWayApplication { public static void main(String[] args) { SpringApplication.run(GateWayApplication.class, args); } @Bean @Order(-1) public GlobalFilter a() { return (exchange, chain) -> { return chain.filter(exchange).then(Mono.fromRunnable(() -> { System.out.println(-1); })); }; } @Bean @Order(0) public GlobalFilter b() { return (exchange, chain) -> { return chain.filter(exchange).then(Mono.fromRunnable(() -> { System.out.println(0); })); }; } @Bean @Order(1) public GlobalFilter c() { return (exchange, chain) -> { return chain.filter(exchange).then(Mono.fromRunnable(() -> { System.out.println(1); })); }; } }
在配置文件类配置两条路由
server.port: 7777 spring: application: name: gateway cloud: gateway: discovery: locator: enabled: true lower-case-service-id: true routes: - id: method_route uri: http://127.0.0.1:9999 predicates: - Method=GET - id: method_route uri: http://127.0.0.1:8006 predicates: - Method=GET
发送请求,请求到达后匹配的是第一条路由,由此可以知道路由匹配的顺序会根据加载的顺序来
4:SpringCloudGateWay从注册中心获得路由
在官方文档中,我们可以看到有这样的一段话
Configuring Predicates and Filters For DiscoveryClient Routes
By default the Gateway defines a single predicate and filter for routes created via a DiscoveryClient.
The default predicate is a path predicate defined with the pattern /serviceId/**, where serviceId is the id of the service from the DiscoveryClient.
The default filter is rewrite path filter with the regex /serviceId/(?
If you would like to customize the predicates and/or filters used by the DiscoveryClient routes you can do so by setting spring.cloud.gateway.discovery.locator.predicates[x] and spring.cloud.gateway.discovery.locator.filters[y]. When doing so you need to make sure to include the default predicate and filter above, if you want to retain that functionality. Below is an example of what this looks like.
地址 :https://cloud.spring.io/spring-cloud-gateway/reference/html/#_global_filters
spring.cloud.gateway.discovery.locator.predicates[0].name: Path spring.cloud.gateway.discovery.locator.predicates[0].args[pattern]: "'/'+serviceId+'/**'" spring.cloud.gateway.discovery.locator.predicates[1].name: Host spring.cloud.gateway.discovery.locator.predicates[1].args[pattern]: "'**.foo.com'" spring.cloud.gateway.discovery.locator.filters[0].name: Hystrix spring.cloud.gateway.discovery.locator.filters[0].args[name]: serviceId spring.cloud.gateway.discovery.locator.filters[1].name: RewritePath spring.cloud.gateway.discovery.locator.filters[1].args[regexp]: "'/' + serviceId + '/(?.*)'" spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remaining}'"
根据文档介绍,依照这种方式,可以从注册中心获得断言与过滤器的配置
5:SpringGateWay从数据库配置路由
public class DBRouteDefinitionRepository implements RouteDefinitionRepository
项目中实现了RouteDefinitionRepository后,springgateway会采用你实现的这个类去加载路由,如果不实现则采用他默认的方式加载路由
public class DBRouteDefinitionRepository implements RouteDefinitionRepository { //保存路由 private final Maproutes = synchronizedMap(new LinkedHashMap ()); private Logger log = LoggerFactory.getLogger(DBRouteDefinitionRepository.class); //初始標準 private boolean init_flag = true; // private final GatewayProperties properties; private DynamicRouteServiceImpl service; public DBRouteDefinitionRepository(GatewayProperties properties) { this.properties = properties; this.service = new DynamicRouteServiceImpl(); } @Override public Flux getRouteDefinitions() { if(init_flag) { List routeDefinitions = new ArrayList<>(); List rs = new ArrayList<>(); try { routeDefinitions = service.quertAllRoutes();//从数据库中加载route rs = this.properties.getRoutes();//获得配置文件的route for (RouteDefinition rse : rs) { routeDefinitions.add(rse); } routes.clear(); routeDefinitions.forEach(x->routes.put(x.getId(), x)); init_flag=false; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); log.error("Init Route Fail,Can't get Routes.",e); } return Flux.fromIterable(routeDefinitions); }else { return Flux.fromIterable(routes.values()); } } @Override public Mono delete(Mono routeId) { return routeId.flatMap(id -> { if (routes.containsKey(id)) { routes.remove(id); return Mono.empty(); } return Mono.defer(() -> Mono.error(new NotFoundException("RouteDefinition not found: "+routeId))); }); } @Override public Mono save(Mono route) { return route.flatMap( r -> { routes.put(r.getId(), r); return Mono.empty(); }); } }
这个是我自己实现的类,这个类可以从数据库与配置文件中获得路由配置,从数据库中获得路由配置可以根据个人的要求来
@Validated public class RouteDefinition { @NotEmpty private String id = UUID.randomUUID().toString(); @NotEmpty @Valid private Listpredicates = new ArrayList<>(); @Valid private List filters = new ArrayList<>(); @NotNull private URI uri; private int order = 0; public RouteDefinition() { } public RouteDefinition(String text) { int eqIdx = text.indexOf('='); if (eqIdx <= 0) { throw new ValidationException("Unable to parse RouteDefinition text '" + text + "'" + ", must be of the form name=value"); } setId(text.substring(0, eqIdx)); String[] args = tokenizeToStringArray(text.substring(eqIdx + 1), ","); setUri(URI.create(args[0])); for (int i = 1; i < args.length; i++) { this.predicates.add(new PredicateDefinition(args[i])); } } public String getId() { return id; } public void setId(String id) { this.id = id; } public List getPredicates() { return predicates; } public void setPredicates(List predicates) { this.predicates = predicates; } public List getFilters() { return filters; } public void setFilters(List filters) { this.filters = filters; } public URI getUri() { return uri; } public void setUri(URI uri) { this.uri = uri; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RouteDefinition routeDefinition = (RouteDefinition) o; return Objects.equals(id, routeDefinition.id) && Objects.equals(predicates, routeDefinition.predicates) && Objects.equals(order, routeDefinition.order) && Objects.equals(uri, routeDefinition.uri); } @Override public int hashCode() { return Objects.hash(id, predicates, uri); } @Override public String toString() { return "RouteDefinition{" + "id='" + id + '\'' + ", predicates=" + predicates + ", filters=" + filters + ", uri=" + uri + ", order=" + order + '}'; } }
感谢各位的阅读!关于“SpringCloudGateway开发的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。