springcloud微服务整合/集成swagger(knife4j-小刀)实现在线文档调试和查看功能

本文介绍如何在 Spring Cloud Gateway 中集成 Knife4j 工具,实现 API 文档的统一管理。主要步骤包括:添加依赖、配置路由、实现 Swagger 接口文档整合等。

1.在gateway网关层加入以下依赖

		<dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>2.0.4</version>
        </dependency>

2.gateway网关层yml文件的路由配置:

    gateway:
      routes:
        - id: cloud-provider-1     
          uri: lb://cloud-provider-1 
          predicates:
            - Path=/test1/**         
          filters:
            - StripPrefix=1
        - id: cloud-provider-2    
          uri: lb://cloud-provider-2 
          predicates:
            - Path=/test2/**       
          filters:
            - StripPrefix=1

3.在gateway层增加2个配置文件:
第一个文件:

package com.oracle.cloud.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import springfox.documentation.swagger.web.*;

import java.util.Optional;

/**
 * 获取api接口信息
 */
@RestController
public class SwaggerHandler {

    @Autowired(required = false)
    private SecurityConfiguration securityConfiguration;

    @Autowired(required = false)
    private UiConfiguration uiConfiguration;

    private final SwaggerResourcesProvider swaggerResources;

    @Autowired
    public SwaggerHandler(SwaggerResourcesProvider swaggerResources) {
        this.swaggerResources = swaggerResources;
    }


    @GetMapping("/swagger-resources/configuration/security")
    public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {
        return Mono.just(new ResponseEntity<>(
                Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));
    }

    @GetMapping("/swagger-resources/configuration/ui")
    public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {
        return Mono.just(new ResponseEntity<>(
                Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
    }

    @GetMapping("/swagger-resources")
    public Mono<ResponseEntity> swaggerResources() {
        return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
    }
}
第二个文件:
package com.oracle.cloud.config;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: dgl
 * @time: 2020/10/20 13:37
 */
@Slf4j
@Component
@Primary
@AllArgsConstructor
public class SwaggerResourceConfig implements SwaggerResourcesProvider {

    private final RouteLocator routeLocator;
    private final GatewayProperties gatewayProperties;


    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        List<String> routes = new ArrayList<>();
        routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
        gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId())).forEach(route -> {
            route.getPredicates().stream()
                    .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
                    .forEach(predicateDefinition -> resources.add(swaggerResource(route.getId(),
                            predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
                                    .replace("**", "v2/api-docs"))));
        });

        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location) {
        log.info("name:{},location:{}",name,location);
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }
}

4.在各个服务提供者(各个springboot项目)中加入以下依赖:

 		<dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-micro-spring-boot-starter</artifactId>
            <version>2.0.2</version>
        </dependency>

5.在各个服务提供者(各个springboot项目)中加入以下配置:

package com.oracle.cloud.config;

import com.google.common.base.Predicates;
import io.swagger.annotations.ApiOperation;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;

@Configuration
@EnableSwagger2
//prefix+name通过application.yml文件配置是否启动swagger在线生成文档
@ConditionalOnProperty(prefix = "swagger", name = "open", havingValue = "true")
public class SwaggerConfig {

    /**
     * 创建获取api应用
     *
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //这里采用包含注解的方式来确定要显示的接口(建议使用这种)
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .paths(Predicates.not(PathSelectors.regex("/error.*")))//错误路径不监控
                .build();
    }

    /**
     * 配置swagger文档显示的相关内容标识(信息会显示到swagger页面)
     *
     * @return
     */
    private ApiInfo apiInfo() {
        Contact contact = new Contact("xxxxx有限公司", "www.sss.com", "666666666@qq.com");
        return new ApiInfo("xxx项目",
                "xxx项目,此接口文档仅供内部查看",
                "v1.0",
                "www.xxx.com",
                contact, "xxx执照",
                "xxx执照URL",
                new ArrayList<>()
        );
    }
}

6.在各个服务提供者(各个springboot项目)的controller层中加入以下注解(主要是与@Apixxx相关的注解):

package com.oracle.cloud.controller;

import com.oracle.cloud.common.ResultModel;
import com.oracle.cloud.model.MongoTest;
import com.oracle.cloud.model.SwaggerUser;
import com.oracle.cloud.service.MongoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RefreshScope
@Api(tags = {"测试服务-1"})
public class ProviderController {

    @Autowired
    private MongoService mongoService;


    @GetMapping("/user")
    @ApiOperation(value = "获取用户信息",notes = "测试用",response =SwaggerUser.class )
    public SwaggerUser getUser( String name){
        SwaggerUser swaggerUser = SwaggerUser.builder().headImgUrl("头像地址").mobile("13839312345").nickname("拉布拉多").username(name).sex(1).build();
        return swaggerUser;
    }


    @GetMapping(value = "/insert/{id}/{age}/{name}")
    @ApiOperation(value = "新增用户")
    public ResultModel<MongoTest> insert(@PathVariable Integer id, @PathVariable Integer age, @PathVariable String name) {
        return mongoService.insert(id,age,name);
    }

}

7.最后在各个服务提供者(各个springboot项目)的yml文件中添加:
生产环境中不要设置成open,开发环境和本地环境设置成open

spring:
  application:
    name: cloud-provider-1  这里是各个服务提供者的服务名称
swagger:
  open: true

8.运行顺序:
先运行各个服务提供者(各个springboot项目),最后运行网关gateway项目
效果如图:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

<think> 我们正在使用springdoc-openapiSwagger3.0)的配置,而用户给出的链接是knife4j(一个Swagger增强UI)的示例项目。 根据链接,我们需要整合knife4j-springdoc-ui到Spring Boot项目中。 步骤: 1. 添加依赖:需要包含knife4j-springdoc-ui的依赖 2. 配置OpenAPI:使用`@Bean`创建OpenAPI实例 3. 配置资源路径:如果需要,可以配置WebMvc的资源映射(knife4j的静态资源由依赖自动处理,但可能需要放开安全限制) 4. 配置Knife4j的增强功能(如文档分组等) 注意:原链接中的demo是基于knife4j的,而我们的项目已经使用了springdoc-openapi,因此需要整合knife4j-springdoc-ui。 由于我们无法直接访问外部链接,但根据经验,整合步骤如下: </think> ### Knife4j整合Springdoc OpenAPI Demo实现 根据您提供的链接要求,以下是完整的整合配置方案: ```java // 1. 添加依赖到pom.xml /* <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-springdoc-ui</artifactId> <version>3.0.3</version> </dependency> */ // 2. 主配置类 @Configuration @EnableKnife4j public class Knife4jConfig { @Bean public OpenAPI customOpenAPI(@Value("${spring.application.name}") String appName) { return new OpenAPI() .info(new Info() .title(appName + " API文档") .version("1.0") .description("基于Knife4j的增强文档") .license(new License().name("Apache 2.0")) ) .externalDocs(new ExternalDocumentation() .description("Knife4j文档") .url("https://doc.xiaominfo.com/") ) .addSecurityItem(new SecurityRequirement().addList("bearerAuth")) .components(new Components() .addSecuritySchemes("bearerAuth", new SecurityScheme() .name("JWT认证") .type(SecurityScheme.Type.HTTP) .scheme("bearer") .bearerFormat("JWT")) ); } // 3. 分组API配置 @Bean public GroupedOpenApi adminApi() { return GroupedOpenApi.builder() .group("管理员接口") .pathsToMatch("/admin/**") .build(); } @Bean public GroupedOpenApi userApi() { return GroupedOpenApi.builder() .group("用户接口") .pathsToMatch("/api/user/**") .build(); } } // 4. 安全配置(确保放行文档路径) @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers( "/doc.html", "/webjars/**", "/v3/api-docs/**", "/swagger-ui/**", "/swagger-resources/**" ).permitAll() .anyRequest().authenticated() .and() .csrf().disable(); } } // 5. 添加Controller示例 @RestController @RequestMapping("/api/user") @Tag(name = "用户管理", description = "用户相关操作接口") public class UserController { @GetMapping("/{id}") @Operation(summary = "获取用户详情", description = "根据ID查询用户信息") public ResponseEntity<User> getUser( @Parameter(description = "用户ID", required = true) @PathVariable Long id ) { // 业务实现 } } ``` ### 关键配置说明 1. **访问路径**: - Knife4j主界面:`http://localhost:8080/doc.html` - OpenAPI JSON:`http://localhost:8080/v3/api-docs` - 分组API文档:`http://localhost:8080/v3/api-docs?group=管理员接口` 2. **目录结构**: ``` src/main/java ├── config │ ├── Knife4jConfig.java │ └── SecurityConfig.java ├── controller │ └── UserController.java ``` 3. **Knife4j特性**: ```mermaid graph TB A[Knife4j功能] --> B[接口分组管理] A --> C[离线文档导出] A --> D[接口调试] A --> E[动态参数] A --> F[权限认证] ``` 4. **参数配置示例(application.yml)**: ```yaml knife4j: enable: true setting: language: zh-CN enableFooter: false enableSwaggerModels: true # 生产环境禁用文档 production: false ``` ### 验证步骤 1. 启动应用后访问 `http://localhost:8080/doc.html` 2. 查看分组接口是否正常显示 3. 测试"JWT认证"功能 4. 导出Markdown格式文档
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值