一、網關基本概念
1、API網關介紹
API 網關出現的原因是微服務架構的出現,不同的微服務一般會有不同的網絡地址,而外部客戶端可能需要調用多個服務的接口才能完成一個業務需求,如果讓客戶端直接與各個微服務通信,會有以下的問題:
(1)客戶端會多次請求不同的微服務,增加了客戶端的復雜性。
(2)存在跨域請求,在一定場景下處理相對復雜。
(3)認證復雜,每個服務都需要獨立認證。
(4)難以重構,隨着項目的迭代,可能需要重新划分微服務。例如,可能將多個服務合並成一個或者將一個服務拆分成多個。如果客戶端直接與微服務通信,那么重構將會很難實施。
(5)某些微服務可能使用了防火牆 / 瀏覽器不友好的協議,直接訪問會有一定的困難。
以上這些問題可以借助 API 網關解決。API 網關是介於客戶端和服務器端之間的中間層,所有的外部請求都會先經過 API 網關這一層。也就是說,API 的實現方面更多的考慮業務邏輯,而安全、性能、監控可以交由 API 網關來做,這樣既提高業務靈活性又不缺安全性
(6)getway可以實現nginx的請求轉發和跨越(@CrossOrigin也可以實現跨越)。

2、Spring Cloud Gateway

網關和服務都在Nacos注冊,注冊之后通過Getway網關在訪問相應的服務
3、Spring Cloud Gateway核心概念
網關提供API全托管服務,豐富的API管理功能,輔助企業管理大規模的API,以降低管理成本和安全風險,包括協議適配、協議轉發、安全策略、防刷、流量、監控日志等貢呢。一般來說網關對外暴露的URL或者接口信息,我們統稱為路由信息。如果研發過網關中間件或者使用過Zuul的人,會知道網關的核心是Filter以及Filter Chain(Filter責任鏈)。Sprig Cloud Gateway也具有路由和Filter的概念。下面介紹一下Spring Cloud Gateway中幾個重要的概念。
(1)路由。路由是網關最基礎的部分,路由信息有一個ID、一個目的URL、一組斷言和一組Filter組成。如果斷言路由為真,則說明請求的URL和配置匹配
(2)斷言。Java8中的斷言函數。Spring Cloud Gateway中的斷言函數輸入類型是Spring5.0框架中的ServerWebExchange。Spring Cloud Gateway中的斷言函數允許開發者去定義匹配來自於http request中的任何信息,比如請求頭和參數等,簡單來講就是一個匹配規則,如果匹配到就到Handler去處理。
(3)過濾器。一個標准的Spring webFilter。Spring cloud gateway中的filter分為兩種類型的Filter,分別是Gateway Filter和Global Filter。過濾器Filter將會對請求和響應進行修改處理,統一異常處理,統一跨域處理等。
如上圖所示,Spring cloud Gateway發出請求。然后再由Gateway Handler Mapping中找到與請求相匹配的路由,將其發送到Gateway web handler。Handler再通過指定的過濾器鏈將請求發送到我們實際的服務執行業務邏輯,然后返回。
二、getway網關例子
1、在infrastructure模塊下創建api_gateway模塊
2、在pom.xml引入依賴
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>infrastructure</artifactId> <groupId>com.stu</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>api_gateway</artifactId> <dependencies> <dependency> <groupId>com.stu</groupId> <artifactId>common-utils</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <!--gson--> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency> <!--服務調用--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> </dependencies> </project>
3、編寫application.properties配置文件
# 服務端口 server.port=8222 # 服務名 spring.application.name=service-gateway # nacos服務地址 spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 #使用服務發現路由,通過openfeign找到服務(nginx是通過配置文件的路徑匹配發現服務) spring.cloud.gateway.discovery.locator.enabled=true #服務路由名小寫 #spring.cloud.gateway.discovery.locator.lower-case-service-id=true #配置service-edu服務 #設置路由id(id可以隨便命名,建議用服務名稱) spring.cloud.gateway.routes[0].id=service-edu #設置路由的uri spring.cloud.gateway.routes[0].uri=lb://service-edu #設置路由斷言,代理servicerId為auth-service的/auth/路徑 spring.cloud.gateway.routes[0].predicates= Path=/eduservice/** #配置service-edu服務 spring.cloud.gateway.routes[1].id=service-msm ## 服務名 #spring.application.name=service-msm spring.cloud.gateway.routes[1].uri=lb://service-msm spring.cloud.gateway.routes[1].predicates= Path=/edumsm/**
yml文件:
server: port: 8222 spring: application: cloud: gateway: discovery: locator: enabled: true routes: - id: SERVICE-ACL uri: lb://SERVICE-ACL predicates: - Path=/*/acl/** # 路徑匹配 - id: SERVICE-EDU uri: lb://SERVICE-EDU predicates: - Path=/eduservice/** # 路徑匹配 - id: SERVICE-UCENTER uri: lb://SERVICE-UCENTER predicates: - Path=/ucenter/** # 路徑匹配 nacos: discovery: server-addr: 127.0.0.1:8848
4、編寫啟動類
package com.stu.getway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient//Nacos注冊 public class ApiGetwayApplication { public static void main(String[] args) { SpringApplication.run(ApiGetwayApplication.class,args); } }
5、測試
通過nginx配置訪問(8001)
通過getw配置訪問(8222)

三、網關相關配置
1、網關解決跨域問題
package com.stu.getway.config; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator; import org.springframework.cloud.gateway.discovery.DiscoveryLocatorProperties; import org.springframework.cloud.gateway.route.RouteDefinitionLocator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.codec.ServerCodecConfigurer; import org.springframework.http.codec.support.DefaultServerCodecConfigurer; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsUtils; import org.springframework.web.cors.reactive.CorsWebFilter; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import org.springframework.web.util.pattern.PathPatternParser; import reactor.core.publisher.Mono; /** * <p> * 處理跨域 * </p> * * @author qy * @since 2019-11-21 */ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsWebFilter; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; import org.springframework.web.util.pattern.PathPatternParser; /** * description: * * @author wangpeng * @date 2019/01/02 */ @Configuration public class CorsConfig { @Bean public CorsWebFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedMethod("*"); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); source.registerCorsConfiguration("/**", config); return new CorsWebFilter(source); } }
2、全局Filter,統一處理會員登錄與外部不允許訪問的服務
package com.stu.getway.filter; import com.google.gson.JsonObject; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.stereotype.Component; import org.springframework.util.AntPathMatcher; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import java.nio.charset.StandardCharsets; import java.util.List; /** * <p> * 全局Filter,統一處理會員登錄與外部不允許訪問的服務 * </p> * * @author qy * @since 2019-11-21 */ @Component public class AuthGlobalFilter implements GlobalFilter, Ordered { private AntPathMatcher antPathMatcher = new AntPathMatcher(); @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest request = exchange.getRequest(); String path = request.getURI().getPath(); //校驗用戶必須登錄 if(antPathMatcher.match("/api/**/auth/**", path)) { List<String> tokenList = request.getHeaders().get("token"); if(null == tokenList) { ServerHttpResponse response = exchange.getResponse(); return out(response); } else { // Boolean isCheck = JwtUtils.checkToken(tokenList.get(0)); // if(!isCheck) { ServerHttpResponse response = exchange.getResponse(); return out(response); // } } } //內部服務接口,不允許外部訪問 if(antPathMatcher.match("/**/inner/**", path)) { ServerHttpResponse response = exchange.getResponse(); return out(response); } return chain.filter(exchange); } @Override public int getOrder() { return 0; } private Mono<Void> out(ServerHttpResponse response) { JsonObject message = new JsonObject(); message.addProperty("success", false); message.addProperty("code", 28004); message.addProperty("data", "鑒權失敗"); byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8); DataBuffer buffer = response.bufferFactory().wrap(bits); //response.setStatusCode(HttpStatus.UNAUTHORIZED); //指定編碼,否則在瀏覽器中會中文亂碼 response.getHeaders().add("Content-Type", "application/json;charset=UTF-8"); return response.writeWith(Mono.just(buffer)); } }
3、自定義異常處理
服務網關調用服務時可能會有一些異常或服務不可用,它返回錯誤信息不友好,需要我們覆蓋處理
ErrorHandlerConfig
package com.stu.getway.handler; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.web.ResourceProperties; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.reactive.error.ErrorAttributes; import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.codec.ServerCodecConfigurer; import org.springframework.web.reactive.result.view.ViewResolver; import java.util.Collections; import java.util.List; /** * 覆蓋默認的異常處理 * * @author yinjihuan * */ @Configuration @EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class}) public class ErrorHandlerConfig { private final ServerProperties serverProperties; private final ApplicationContext applicationContext; private final ResourceProperties resourceProperties; private final List<ViewResolver> viewResolvers; private final ServerCodecConfigurer serverCodecConfigurer; public ErrorHandlerConfig(ServerProperties serverProperties, ResourceProperties resourceProperties, ObjectProvider<List<ViewResolver>> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer, ApplicationContext applicationContext) { this.serverProperties = serverProperties; this.applicationContext = applicationContext; this.resourceProperties = resourceProperties; this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList); this.serverCodecConfigurer = serverCodecConfigurer; } @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) { JsonExceptionHandler exceptionHandler = new JsonExceptionHandler( errorAttributes, this.resourceProperties, this.serverProperties.getError(), this.applicationContext); exceptionHandler.setViewResolvers(this.viewResolvers); exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters()); exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders()); return exceptionHandler; } }
JsonExceptionHandler
package com.stu.getway.handler; import org.springframework.boot.autoconfigure.web.ErrorProperties; import org.springframework.boot.autoconfigure.web.ResourceProperties; import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler; import org.springframework.boot.web.reactive.error.ErrorAttributes; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpStatus; import org.springframework.web.reactive.function.server.*; import java.util.HashMap; import java.util.Map; /** * 自定義異常處理 * * <p>異常時用JSON代替HTML異常信息<p> * * @author yinjihuan * */ public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler { public JsonExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties errorProperties, ApplicationContext applicationContext) { super(errorAttributes, resourceProperties, errorProperties, applicationContext); } /** * 獲取異常屬性 */ @Override protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) { Map<String, Object> map = new HashMap<>(); map.put("success", false); map.put("code", 20005); map.put("message", "網關失敗"); map.put("data", null); return map; } /** * 指定響應處理方法為JSON處理的方法 * @param errorAttributes */ @Override protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) { return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse); } /** * 根據code獲取對應的HttpStatus * @param errorAttributes */ @Override protected int getHttpStatus(Map<String, Object> errorAttributes) { return 200; } }