符合中小企业对网站设计、功能常规化式的企业展示型网站建设
本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...
商城网站建设因基本功能的需求不同费用上面也有很大的差别...
手机微信网站开发、微信官网、微信商城网站...
这篇文章给大家分享的是有关SpringCloudGateway开发的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
创新互联是一家集网站建设,文登企业网站建设,文登品牌网站建设,网站定制,文登网站建设报价,网络营销,网络优化,文登网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。
路由简介:
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开发的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!