從零搭建Spring Cloud Gateway閘道器(一)
阿新 • • 發佈:2020-03-18
# 新建Spring Boot專案
怎麼新建Spring Boot專案這裡不再具體贅述,不會的可以翻看下之前的部落格或者直接百度。這裡直接貼出對應的pom檔案。
pom依賴如下:
```xml
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.2.5.RELEASE
com.lifengdi
gateway
0.0.1-SNAPSHOT
gateway
Demo project for Spring Boot
1.8
Hoxton.SR3
org.springframework.cloud
spring-cloud-starter-gateway
org.projectlombok
lombok
1.18.12
true
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.cloud
spring-cloud-starter-netflix-hystrix
org.springframework.boot
spring-boot-starter-actuator
org.apache.commons
commons-pool2
commons-io
commons-io
2.5
compile
com.alibaba
fastjson
1.2.58
org.springframework.boot
spring-boot-starter-mail
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
```
由於是閘道器專案,所以不需要`spring-boot-starter-web`相關的依賴。
配置檔案如下:
```yaml
server:
port: 8080
spring:
application:
name: spring-cloud-gateway-demo
cloud:
gateway:
discovery:
locator:
enabled: true #啟用路由訪問
routes:
- id: path_route
# 指定域名
uri: http://localhost:8081
predicates:
- Path=/jar/**
filters:
# 熔斷配置
- name: Hystrix
args:
name: default
fallbackUri: forward:/fallback
- id: path_route2
# 指定域名
uri: http://localhost:8082
predicates:
- Path=/war/**
filters:
# 熔斷配置
- name: Hystrix
args:
name: hystrix1
fallbackUri: forward:/fallback
mvc:
throw-exception-if-no-handler-found: true
# 預設熔斷超時時間30s
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 3000
hystrix1:
execution:
isolation:
thread:
timeoutInMilliseconds: 1000
```
# 熔斷(介面或者專案)
熔斷相關jar包如下:
```xml
org.springframework.cloud
spring-cloud-starter-netflix-hystrix
```
預設的熔斷回撥介面:
```java
package com.lifengdi.gateway.hystrix;
import com.lifengdi.gateway.exception.BaseException;
import com.lifengdi.gateway.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author: Li Fengdi
* @date: 2020-03-18 16:35
*/
@RestController
@Slf4j
public class DefaultHystrixController {
@RequestMapping("/fallback")
public ResponseResult