knife4j,微服务聚合Swagger文档

本文介绍了如何使用Spring Cloud Gateway和knife4j在微服务架构中实现API文档的聚合。通过Nacos作为注册中心,创建了micro-knife4j-gateway作为网关,聚合了micro-knife4j-user和micro-knife4j-order服务的Swagger文档。详细步骤包括服务的依赖配置、Swagger的集成以及如何在网关上实现文档切换。此外,还提供了如何切换回原始Swagger UI的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前置知识

我们将采用Nacos作为注册中心,Gateway作为网关,使用knife4j来生成API文档,对这些技术不了解的朋友可以看下下面的文章。

应用架构

我们理想的解决方案应该是这样的,网关作为API文档的统一入口,网关聚合所有微服务的文档,通过在网关进行切换来实现对其他服务API文档的访问。

相关服务划分:

  • micro-knife4j-gateway:网关服务,作为微服务API文档的访问入口,聚合所有API文档,需要引入文档前端UI包;

  • micro-knife4j-user:用户服务,普通API服务,不需要引入文档前端UI包;

  • micro-knife4j-order:订单服务,普通API服务,不需要引入文档前端UI包。

具体实现

下面详细介绍下Spring Cloud Gateway + knife4j 聚合API文档的具体实现,依次搭建用户服务、订单服务和网关服务。

micro-knife4j-user

我们首先来搭建用户服务,一个普通的API服务,很简单,仅需三步即可集成knife4j。

  • pom.xml中添加相关依赖,一个SpringBoot的web功能依赖,knife4j的微服务依赖(不包含API文档的前端UI包);

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-micro-spring-boot-starter</artifactId>
    </dependency>
</dependencies>
  • application.yml这添加相关配置,配置一下Nacos注册中心即可;

server:
  port: 9501
spring:
  profiles:
    active: dev
  application:
    name: micro-knife4j-user
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
management:
  endpoints:
    web:
      exposure:
        include: "*"
  • 添加Swagger相关配置,非常常规的配置,添加@EnableKnife4j注解开启knife4j的增强功能。

/**
 * Swagger API相关配置
 */
@Configuration
@EnableSwagger2
@EnableKnife4j
public class Swagger2Config {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
      &nbs
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

图书馆的小盆友

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值