1、新建Module

2、POM

  1. <dependencies>
  2. <!--gateway-->
  3. <dependency>
  4. <groupId>org.springframework.cloud</groupId>
  5. <artifactId>spring-cloud-starter-gateway</artifactId>
  6. </dependency>
  7. <!--eureka-client-->
  8. <dependency>
  9. <groupId>org.springframework.cloud</groupId>
  10. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  11. </dependency>
  12. <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
  13. <dependency>
  14. <groupId>com.atguigu.springcloud</groupId>
  15. <artifactId>cloud-api-commons</artifactId>
  16. <version>${project.version}</version>
  17. </dependency>
  18. <!--一般基础配置类-->
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-devtools</artifactId>
  22. <scope>runtime</scope>
  23. <optional>true</optional>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.projectlombok</groupId>
  27. <artifactId>lombok</artifactId>
  28. <optional>true</optional>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-test</artifactId>
  33. <scope>test</scope>
  34. </dependency>
  35. </dependencies>

3、YML

  1. server:
  2. port: 9527
  3. spring:
  4. application:
  5. name: cloud-gateway //应用类名称
  6. eureka:
  7. instance:
  8. hostname: cloud-gateway-service
  9. client: #服务提供者provider注册进eureka服务列表内
  10. service-url:
  11. register-with-eureka: true
  12. fetch-registry: true
  13. defaultZone: http://localhost:7001/eureka

4、业务类

5、主启动类

image.png

6、9527网关如何做路由映射

1、cloud-provider-payment8001看看controller的访问地址

Get
lb

2、我们目前不想暴露8001端口,希望在8001外面套一层9527

7、YML新增网关配置

  1. server:
  2. port: 8001
  3. spring:
  4. application:
  5. name: cloud-payment-service
  6. datasource:
  7. type: com.alibaba.druid.pool.DruidDataSource
  8. driver-class-name: com.mysql.jdbc.Driver
  9. url: jdbc:mysql://localhost:3306/user_db?useUnicode=true&characterEncoding=utf-8&useSSL=false
  10. username: root
  11. password: root
  12. mybatis:
  13. mapper-locations: classpath:mapper/*.xml
  14. type-aliases-package: com.zxd.springcloud.entities #所有Entity别名类所在包
  15. eureka:
  16. client:
  17. #表示是否将自己注册进EurekaServer默认为true。
  18. register-with-eureka: true
  19. #是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
  20. fetchRegistry: true
  21. service-url:
  22. #单机版
  23. defaultZone: http://localhost:7001/eureka
  24. # 集群版
  25. #defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
  26. instance:
  27. instance-id: payment8001
  28. #访问路径可以显示IP地址
  29. prefer-ip-address: true
  30. #Eureka客户端向服务端发送心跳的时间间隔,单位为秒(默认是30秒)
  31. #lease-renewal-interval-in-seconds: 1
  32. #Eureka服务端在收到最后一次心跳后等待时间上限,单位为秒(默认是90秒),超时将剔除服务
  33. #lease-expiration-duration-in-seconds: 2

8、测试

添加网关前
http://localhost:8001/payment/get/31

添加网关后
http://localhost:9527/payment/get/31

9、YML配置说明

image.png

Gayway网关路由配置有两种方法