SpringCloud Gateway 聚合各个微服务的knife4j doc文档

背景

微服务中,每个服务都引入生成doc文档,但我们想从网关处统一入口,那就需要聚合各个微服务的doc文档,由网关统一访问。本文使用的是knife4j,knife4j作者提供了聚合包, 传送门。

实现

  1. 网关引入依赖(各微服务按照正常的knife4j配置能访问doc.html即可)。knife4j版本 4.3.0, cloud版本2022.0.2,springboot版本3.1.0
    此处源码使用的是gradle catalogs统一定义依赖,详细介绍可见gradle统一定义依赖。各位自己按照自己方式引入即可。
knife4j = "4.3.0"
knife4j = { module = "com.github.xiaoymin:knife4j-openapi3-jakarta-spring-boot-starter", version.ref = "knife4j" }
knife4j-gateway = { module = "com.github.xiaoymin:knife4j-gateway-spring-boot-starter", version.ref = "knife4j" }
  1. 在网关的application.yaml添加knife4j配置,下面是我的网关配置文件
server:
  port: 11000
spring:
  application:
    name: lp-gateway
---
spring:
  cloud:
    # 网关配置
    gateway:
      print-log: true
      authExcludes: 
        - /doc.html
        - /swagger-resources
        - /webjars/**
        - /**/api-docs/**
        - /lp-app/extend/link/**
      ## 自动路由
      discovery:
        locator:
          lowerCaseServiceId: true
          enabled: false
      ## 路由转发配置
      routes:
       - id: lp-auth
         uri: lb://lp-auth
         predicates:
           - Path=/lp-auth/**
         filters:
           #- StripPrefix=1
       - id: lp-system
         uri: lb://lp-system
         predicates:
           - Path=/lp-system/**
         filters:
           #- StripPrefix=1
       - id: lp-app
         uri: lb://lp-app
         predicates:
           - Path=/lp-app/**
         filters:
           #- StripPrefix=1
       - id: lp-workflow
         uri: lb://lp-workflow
         predicates:
           - Path=/lp-workflow/**
         filters:
           #- StripPrefix=1
      ## 全局跨域配置
      globalcors:
        add-to-simple-url-handler-mapping: true
        corsConfigurations:
          '[/**]':
            allowedOriginPatterns: "*"
            allowedMethods:
              - "GET"
              - "POST"
              - "DELETE"
              - "PUT"
              - "OPTIONS"
            allowedHeaders: "*"
            allowCredentials: true
            maxAge: 360000
# 聚合服务的swagger
knife4j:
  # 聚合swagger文档
  gateway:
  	# 是否启用
    enabled: ${knife4j.enable}
    # 指定手动配置的模式(默认为该模式)
    strategy: manual
    routes:
      - name: 登录授权服务
        # 真实子服务访问url地址-提供OpenAPI的文档
        url: /lp-auth/v3/api-docs
        service-name: lp-auth
        # 路由前缀
        context-path: /lp-auth
        order: 1
      - name: 系统服务
        url: /lp-system/v3/api-docs
        service-name: lp-system
        # 路由前缀
        context-path: /lp-system
        order: 2
      - name: 应用服务
        url: /lp-app/v3/api-docs
        service-name: lp-app
        # 路由前缀
        context-path: /lp-app
        order: 3
      - name: 流程服务
        url: /lp-workflow/v3/api-docs
        service-name: lp-workflow
        # 路由前缀
        context-path: /lp-workflow
        order: 4
  1. 访问网关的ip:port/xx/doc.html即可
    SpringCloud Gateway 聚合各个微服务的knife4j doc文档_第1张图片

你可能感兴趣的:(微服务,spring,boot,spring,cloud)