swagger和knife4j常用配置

一、swagger

1、添加依赖

版本注意事项见一下连接:解决方案之‘Failed to start bean ‘documentationPluginsBootstrapper‘; nested exception is java.lang.NullPoi_循环网络不循环的博客-CSDN博客

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

2、编写配置类

package cn.wn.swagger;
//1. 配置类
@Configuration
//2. 开启swagger支持
@EnableSwagger2
public class SwaggerApp {
    /**
     * 3、自动创建Docket文档摘要对象
     */
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2) // 选择swagger的版本
                // 配置文档信息:swagger文档的标题、版本、描述
                .apiInfo(this.apiInfo())
                .select()
                // 配置要生成swagger文档的扫描的目录包
                .apis(RequestHandlerSelectors.basePackage("com.woniu.web"))
                // 对指定路径下的任意类生成文档
                .paths(PathSelectors.any())
                // 创建对象
                .build();
    }
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                // 指定文档标题 (在swagger页面会显示)
                .title("SpringBoot中使用Swagger构建接口文件")
                // 指定文档的版本
                .version("1.0")
                // 文档描述
                .description("API描述").build();
    }
}

3、访问链接

http://localhost:8080/swagger-ui.html


二、knife4j

1、添加依赖

<!--添加knife4j的启动器-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>

2、访问链接

 http://localhost:8080/doc.html


三、网关聚合knife4j

1、网关

(1)依赖

<dependency>
            <groupId>com.woniu</groupId>
            <artifactId>sk-common-jwt</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

(2)SwaggerConfig

@Component
@Primary // 当有多个bean时候,优先使用当前bean
@AllArgsConstructor
public class SwaggerConfig 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<>();
        //获取所有路由的ID
        routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
        //过滤出配置文件中定义的路由->过滤出Path Route Predicate->根据路径拼接成api-docs路径->生成SwaggerResource
        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) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }
}

(3)SwaggerHandler

@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)));
    }
}

(4)yml配置

这里配置的是需要进行聚合的服务的路由,这个路由一定要配并且网关一定要连接上nacos,不然网关聚合就会失效。

spring:
    cloud:
        nacos:
          discovery:
            server-addr: http://localhost:8848
        gateway:
          routes:
            - id: api-siot-service
              uri: lb://siot-service
              predicates:
                - Path=/siot-service/**
              filters:
            - StripPrefix=1

2、其它微服务

(1)依赖

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

(2)配置类

@Configuration
@EnableKnife4j
@EnableSwagger2WebMvc
public class SwaggerConfig {
    /**
     * 3、自动创建Docket文档摘要对象
     */
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2) // 选择swagger的版本
                // 配置文档信息:swagger文档的标题、版本、描述
                .apiInfo(this.apiInfo())
                .select()
                // 配置要生成swagger文档的扫描的目录包
                .apis(RequestHandlerSelectors.basePackage("com.woniu.sk.member.controller"))
                // 对指定路径下的任意类生成文档
                .paths(PathSelectors.any())
                // 创建对象
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                // 指定文档标题 (在swagger页面会显示)
                .title("会员微服务")
                // 指定文档的版本
                .version("1.0")
                // 文档描述
                .description("API描述").build();
    }
}

四、常见错误

1、knife4j不显示controller层的方法

原因:没有写    @PostMapping注解导致knife4j无法扫描到

2、knife4j 报错404

解决链接:

https://juejin.cn/post/6986247039436718087

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小海海不怕困难

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

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

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

打赏作者

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

抵扣说明:

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

余额充值