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服務上了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM