API網關
API網關是一種設計模式,一種在微服務體系下的經典構件。要了解最新API網關模式可以參考敖小劍寫的《Service Mesh和Api Gateway關係深度探討》
早期SOA階段,也是有API網關的,比如開放平臺接口包含了一系列功能,比如淘寶提供了用戶授權能力、電商能力、支付能力、快遞能力、發票能力、商品管理能力等很多能力,也必然是有多個SOA服務提供,都從統一的網關服務https://eco.taobao.com/router/rest(這是淘寶API的最新接口,不是早期的接口)暴露出來的。
微服務場景下API網關的使用度更高,一些小型的業務接口也往往分散在多個後端服上,爲了達到接口的統一管理、權限驗證、通用處理都需要API網關的存在。有些設計上還會重度依賴API網關做業務隔離、訂號生成、set化路由等。
API網關常見的開源實現包括:nginx、spring cloud zuul、spring cloud gateway、kong等,雲服務廠商也都有API網關服務,比如阿里雲、Aws、Azure有API網關產品。
config文件方式配置
把請求路由到http://httpbin.org:80的yml配置:
spring:
cloud:
gateway:
routes:
- id: default_path_to_httpbin
uri: http://httpbin.org:80
order: 10000
predicates:
- Path=/**
java代碼方式配置
通過java代碼配置路由到http://httpbin.org:80
@SpringBootConfiguration
@EnableAutoConfiguration
public class GatewayTestApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayTestApplication.class, args);
}
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
//@formatter:off
// String uri = "http://httpbin.org:80";
// String uri = "http://localhost:9080";
return builder.routes()
.route(r -> r.path("/**").uri("http://httpbin.org:80"))
.build();
//@formatter:on
}
}
動態服務發現方式配置
添加Netflix eureka client依賴:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
添加 @EnableDiscoveryClient
@SpringBootApplication
@EnableDiscoveryClient
public class SpringCloudGatewayExamplesLbApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudGatewayExamplesLbApplication.class, args);
}
}
添加eureka 服務發現配置
# use eureka discovery, so add eureka discovery server config
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
enabled: true
instance:
prefer-ip-address: true
# open gateway discovery locator and close non-flux loadbalancer
spring:
application:
name: spring-cloud-gateway
cloud:
gateway:
discovery:
locator:
enabled: true
loadbalancer:
ribbon:
enabled: false
所有http://localhost:8080/EXAMPLE-SERVICE/hello
形式的請求會自動發現服務名爲EXAMPLE-SERVICE的服務提供者,併發送http://localhost:890/hello
請求。