zl程序教程

您现在的位置是:首页 >  其他

当前栏目

动态路由配置

2023-04-18 14:39:06 时间

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](https://links.jianshu.com/go?to=http%3A%2F%2Flocalhost%3A9999%2Fmall-

consumer%2Fconsumer%2Fbrand%2F1),网关会根据我们配置的规则帮我们转发到

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

conmuser的服务。