這篇文章給大家分享的是有關(guān)SpringCloudGateway開發(fā)的示例分析的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
創(chuàng)新互聯(lián)是一家集網(wǎng)站建設(shè),文登企業(yè)網(wǎng)站建設(shè),文登品牌網(wǎng)站建設(shè),網(wǎng)站定制,文登網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,文登網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競爭力。可充分滿足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。
路由簡介:
1.SpringCloudGateWay 是用于替代zuul作為API網(wǎng)關(guān),在gateway中有三個(gè)重要的名詞:過濾器,斷言,路由
過濾器與斷言是路由的一部分,路由便是將請求進(jìn)行一系列的處理后分發(fā)到各個(gè)服務(wù)的一個(gè)過程。
路由的過程:首先會加載斷言以及路由,在接受到請求后根據(jù)斷言加載的順序會匹配到先加載的斷言,只有與斷言匹配了的請求才會進(jìn)入路由,沒有匹配到的服務(wù)會將請求當(dāng)成普通的訪問請求。
2:路由加載斷言的方式:
斷言加載的方式有四種,分別是配置文件,java編碼,數(shù)據(jù)庫以及注冊中心
第一種配置文件:
在官方文檔中主要介紹的就是配置文件的加載方式
官方地址:https://cloud.spring.io/spring-cloud-gateway/reference/html/#gateway-starter
一般的斷言有三種要素:id,uri,predicate.
id是斷言的標(biāo)識,uri是ip+端口,predicate則是斷言匹配的規(guī)則
3:示例:
新建一個(gè)springboot項(xiàng)目,并且引入springcloudgateway的依賴
org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-starter-gateway
在啟動類注冊三個(gè)全局過濾器
@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
發(fā)送請求,請求到達(dá)后匹配的是第一條路由,由此可以知道路由匹配的順序會根據(jù)加載的順序來
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}'"
根據(jù)文檔介紹,依照這種方式,可以從注冊中心獲得斷言與過濾器的配置
5:SpringGateWay從數(shù)據(jù)庫配置路由
public class DBRouteDefinitionRepository implements RouteDefinitionRepository
項(xiàng)目中實(shí)現(xiàn)了RouteDefinitionRepository后,springgateway會采用你實(shí)現(xiàn)的這個(gè)類去加載路由,如果不實(shí)現(xiàn)則采用他默認(rèn)的方式加載路由
public class DBRouteDefinitionRepository implements RouteDefinitionRepository { //保存路由 private final Maproutes = synchronizedMap(new LinkedHashMap ()); private Logger log = LoggerFactory.getLogger(DBRouteDefinitionRepository.class); //初始標(biāo)準(zhǔn) 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();//從數(shù)據(jù)庫中加載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(); }); } }
這個(gè)是我自己實(shí)現(xiàn)的類,這個(gè)類可以從數(shù)據(jù)庫與配置文件中獲得路由配置,從數(shù)據(jù)庫中獲得路由配置可以根據(jù)個(gè)人的要求來
@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 + '}'; } }
感謝各位的閱讀!關(guān)于“SpringCloudGateway開發(fā)的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!