1. 程式人生 > 實用技巧 >Spring Cloud GateWay簡單示例

Spring Cloud GateWay簡單示例

前提:提供一個註冊中心,可以使用Eureka Server。供gateway轉發請求時獲取服務例項。

一、新建GateWay專案

1、引入maven依賴

<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>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2、在主類上啟用服務發現註冊註解 @EnableDiscoveryClient

3、配置檔案application.yml內容如下:

# 註冊中心
eureka:
  client:
    service-url:
      defaultZone: http://test:123456@localhost:9090/os/eureka/
    fetch-registry: true
    register-with-eureka: true

spring:
  application:
    name: gateway-service
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true # 服務名小寫
      routes:
        - id: consumer-service  #路由的ID,沒有固定規則但求唯一,建議配合服務名
          uri: lb://consumer-service # 匹配後提供服務的路由地址,lb代表從註冊中心獲取服務,且以負載均衡方式轉發
          predicates:
            - Path=/consumer/** #斷言,路徑相匹配的進行路由
          filters: # 加上StripPrefix=1,否則轉發到後端服務時會帶上consumer字首
            - StripPrefix=1

server:
  port: 9999

# 暴露監控端點
management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: always

二、新建服務提供者專案ConsumerService

1、引入maven依賴

<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>

2、在主類上啟用服務發現註冊註解 @EnableDiscoveryClient

3、application.yml內容如下:

server:
  port: 9700

spring:
  application:
    name: consumer-service 

eureka:
  client:
    service-url:
      defaultZone: http://test:123456@localhost:9090/os/eureka/
    fetch-registry: true
    register-with-eureka: true

4、新建 IndexController ,新增一個 hello 方法,傳入name引數,訪問後返回 hi + name 字串

@RestController
public class IndexController {

    @RequestMapping("/hello")
    public String hello(String name){
        return "hi " + name;
    }
}

5、啟動eureka、gateway、consumerservice,gateway和consumerservice都註冊在eureka了。

通過閘道器訪問consumer-service的hello方法,http://localhost:9999/consumer/hello?name=zy,效果如下,說明請求已經轉發到consumer-service服務上了。