Spring Cloud Gateway是Spring Cloud官方推出的第二代網(wǎng)關框架捺疼,取代Zuul網(wǎng)關女揭。網(wǎng)關作為流量的,在微服務系統(tǒng)中有著非常作用溉仑,網(wǎng)關常見的功能有路由轉(zhuǎn)發(fā)、權限校驗兽愤、限流控制等作用彼念。
項目結構
項目 | 端口 | 描述 |
---|---|---|
eureka-server | 8761 | 服務的注冊與發(fā)現(xiàn) |
service-one | 8081 | 服務 |
gateway-client | 8080 | 網(wǎng)關 gateway |
eureka-server
eureka-server項目非常簡單 引入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
啟動類里面
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
配置文件
spring:
application:
name: eureka-server
server:
port: 8761
eureka:
instance:
hostname: localhostname
client:
fetch-registry: false
register-with-eureka: false
service-url:
defaultZone: http://localhost:8761/eureka/
service-one 項目
搭建非常簡單,添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
啟動類里面
@EnableEurekaClient
@SpringBootApplication
public class ServiceOneApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceOneApplication.class, args);
}
}
配置文件
spring:
application:
name: service-one
server:
port: 8081
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
創(chuàng)建類控制器 UserController浅萧,http://localhost:8081/user/who
@RequestMapping("/user")
@RestController
public class UserController {
@RequestMapping("who")
public String who() {
return "my name is liangwang";
}
}
創(chuàng)建類控制器OrderController逐沙,http://localhost:8081/order/info
@RequestMapping("/order")
@RestController
public class OrderController {
@RequestMapping("/info")
public String orderInfo() {
return "order info date : " + new Date().toString();
}
}
gateway-client項目
使用的是Finchley.SR2版本的,其中已經(jīng)包含了 spring-boot-starter-webflux
添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
使用RouteLocator的Bean進行路由轉(zhuǎn)發(fā)洼畅,將請求進行處理吩案,最后轉(zhuǎn)發(fā)到目標的下游服務
@SpringBootApplication
public class GatewayClientApplication {
@Value("${test.uri}")
private String uri;
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
//basic proxy
.route(r -> r.path("/order/**")
.uri(uri)
).build();
}
public static void main(String[] args) {
SpringApplication.run(GatewayClientApplication.class, args);
}
}
上面的代碼里是在訪問http://localhost:8080/order/的時候,網(wǎng)關轉(zhuǎn)發(fā)到http://service-one:8081/order/帝簇,service-one服務在eureka中有注冊徘郭,最終是對應服務的ip:port
使用配置文件
application.yml
test:
uri: lb://service-one
spring:
application:
name: gateway-client
cloud:
gateway:
routes:
- id: route_service_one
uri: ${test.uri} # uri以lb://開頭(lb代表從注冊中心獲取服務),后面接的就是你需要轉(zhuǎn)發(fā)到的服務名稱
predicates:
- Path=/user/**
server:
port: 8080
logging:
level:
org.springframework.cloud.gateway: TRACE
org.springframework.http.server.reactive: DEBUG
org.springframework.web.reactive: DEBUG
reactor.ipc.netty: DEBUG
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
其中test.uri是我自定義的屬性丧肴,uri以lb://開頭(lb代表從注冊中心獲取服務)残揉,后面接的就是你需要轉(zhuǎn)發(fā)到的服務名稱,按照上面的配置是http://localhost:8080/usr/** => http://service-one:8081/user/** 到此項目搭建完成芋浮,接下來測試了抱环,依次啟動eureka-server、service-one纸巷、gateway-client
訪問
不啟用注冊中心
即使集成了eureka-client也不想使用注冊中心服務镇草,可以關閉
eureka.client.enabled=false
StripPrefix屬性的使用
按照上面的配置,每一個路由只能對應一個控制器的轉(zhuǎn)發(fā)瘤旨,不夠靈活梯啤,假如我想讓userapi的請求都轉(zhuǎn)到service-one服務,比如:
- http://localhost:8080/userapi/user/who => http://localhost:8081/user/who
-
http://localhost:8080/userapi/order/info => http://localhost:8081/order/info
在路由配置上增加StripPrefix=1
spring:
application:
name: gateway-client
cloud:
gateway:
routes:
- id: route_service_one
uri: ${test.uri} # uri以lb://開頭(lb代表從注冊中心獲取服務)存哲,后面接的就是你需要轉(zhuǎn)發(fā)到的服務名稱
predicates:
- Path=/userapi/**
filters:
- StripPrefix=1 # 表示在轉(zhuǎn)發(fā)時去掉userapi
修改完配置因宇,重啟gateway-client項目:
使用Hystrix
在gateway-client項目中引入依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在spring cloud gateway中可以使用Hystrix。Hystrix是 spring cloud中一個服務熔斷降級的組件祟偷,在微服務系統(tǒng)有著十分重要的作用羽嫡。
Hystrix是 spring cloud gateway中是以filter的形式使用的,代碼如下:
@SpringBootApplication
public class GatewayClientApplication {
@Value("${test.uri}")
private String uri;
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
//basic proxy
.route(r -> r.path("/order/**")
.uri(uri)
)
.route(r -> r.path("/user/**")
.filters(f -> f
.hystrix(config -> config
.setName("myserviceOne")
.setFallbackUri("forward:/user/fallback")))
.uri(uri)).build();
}
public static void main(String[] args) {
SpringApplication.run(GatewayClientApplication.class, args);
}
}
上面代碼中添加了一個路由并配置了hystrix的fallbackUri肩袍,新添加一個FallBackController控制器
@RestController
public class FallBackController {
@RequestMapping("/user/fallback")
public Mono<String> fallback() {
return Mono.just("service error, jump fallback");
}
}
重啟gateway-client項目杭棵,并關閉service-one服務,在瀏覽器訪問 http://localhost:8080/user/who
使用yml配置Hystrix
spring:
application:
name: gateway-client
cloud:
gateway:
routes:
- id: route_service_one
uri: ${test.uri} # uri以lb://開頭(lb代表從注冊中心獲取服務),后面接的就是你需要轉(zhuǎn)發(fā)到的服務名稱
predicates:
- Path=/userapi/**
filters:
- StripPrefix=1 # 表示在轉(zhuǎn)發(fā)時去掉userapi
- id: userapi2_route
uri: ${test.uri}
predicates:
- Path=/userapi2/**
filters:
- StripPrefix=1
- name: Hystrix
args:
name: myfallbackcmd
fallbackUri: forward:/user/fallback
在配置中增加了一個新的路由userapi2_route魂爪,還配置了Hystrix先舷,當發(fā)生錯誤時會轉(zhuǎn)發(fā)到fallbackUri,測試訪問 http://localhost:8080/userapi2/order/info
reference
Hystrix wiki
Spring Cloud Gateway
Redis RateLimiter
轉(zhuǎn)載Redis RateLimiter實現(xiàn)