空无以求全
宁静以致远
当前位置:首页 > .html

Nacos+Spring Cloud Gateway动态路由配置

作者:大熊空间发布时间:2022-02-19 17:09分类: 浏览:231评论:0


导读:Nacos+Spring Cloud Gateway动态路由配置 1启动我们的Nacos,配置我们服务需要配置文件。 nacos配置列表 image.png比如youlai-gat...

Nacos+Spring Cloud Gateway动态路由配置

1启动我们的Nacos,配置我们服务需要配置文件。

nacos配置列表

image.png

比如youlai-gateway.yaml网关配置文件。

网关的配置文件

youlai-gateway.yml

spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true # 启用服务发现
          lower-case-service-id: true
      routes:
        - id: mall-consumer
          uri: lb://mall-consumer
          predicates:
            - Path=/consumer/brand/**
          filters:
            - SwaggerHeaderFilter
            - StripPrefix=1
        - id: youlai-auth
          uri: lb://youlai-auth
          predicates:
            - Path=/youlai-auth/**
          filters:
            - SwaggerHeaderFilter
            - StripPrefix=1
        - id: mall-pms
          uri: lb://mall-pms
          predicates:
            - Path=/mall-pms/**
          filters:
            - SwaggerHeaderFilter
            - StripPrefix=1
        - id: mall-ums
          uri: lb://mall-ums
          predicates:
            - Path=/mall-ums/**
          filters:
            - SwaggerHeaderFilter
            - StripPrefix=1

bootstrap.yml

spring:
 application:
 name: youlai-gateway
 cloud:
 nacos:
  注册中心
 discovery:
 server-addr: http://localhost:8848
 配置中心
 config:
 server-addr: ${spring.cloud.nacos.discovery.server-addr}
 file-extension: yaml

mall-consumer的配置文件

mall-consumer.yaml

 datasource:
 type: com.alibaba.druid.pool.DruidDataSource
 driver-class-name: com.mysql.cj.jdbc.Driver
 url: jdbc:mysql://127.0.0.1:3306/mall?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true
 username: root
 password: 514730

bootstrap.yml

 application:
 name: mall-consumer
 cloud:
 nacos:
 discovery:
 server-addr: http://localhost:8848
 config:
 server-addr: ${spring.cloud.nacos.discovery.server-addr}
 file-extension: yaml

2项目的目录结构

image.png

3同理我们需要添加mall-pms的配置文件,同上

2三个服务的端口分别为:

youlai-gateway:9999

mall-consumer:9602

youlai-pms:8602

image.png

3测试

依次启动我们的gateway服务,mall-consumer服务

输入http://localhost:9999/mall-consumer/consumer/brand/1,网关会根据我们配置的规则帮我们转发到

http://localhost:9602/consumer/brand/1这个路径上去。也就是9602这个端口服务被转发成了mall-conmuser的服务。

image.png

Spring Cloud Gateway作用不光只是简单的跳转重定向,还可以实现用户的验证登录,解决跨域,日志拦截,权限控制,限流,熔断,负载均衡,黑名单和白名单机制等。是微服务架构不二的选择

参考:https://www.cnblogs.com/jian0110/p/12862569.html

https://github.com/hxrui/youlai-mall


发表评论: