springBoot和springCloud快速集成swagger

swagger的作用

  • 自動生成REST API文檔,隨着代碼自動更新。
  • 提供了UI界面,既展示接口信息(在線查看),又提供了參數校驗,測試功能(在線調試)。

springBoot集成swagger

  • pom下添加依賴
  <!--springfox -->
      <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger-ui</artifactId>
          <version>2.6.1</version>
      </dependency>
  <!--swagger2-->
      <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger2</artifactId>
          <version>2.6.1</version>
      </dependency>
  • 添加swagger配置
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    /**
     * swagger2的配置文件,這裏可以配置swagger2的一些基本的內容,比如掃描的包等等
     * @return
     */
    @Bean
    public Docket zxApi() {
        ParameterBuilder aParameterBuilder = new ParameterBuilder();//添加全局參數
        aParameterBuilder.name("authorization").defaultValue("token").description("驗證TOKEN").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        List<Parameter> aParameters = new ArrayList<Parameter>();
        aParameters.add(aParameterBuilder.build());
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(zxApiInfo())
                .groupName("測試")  //分組
                .genericModelSubstitutes(DeferredResult.class)
                .useDefaultResponseMessages(false)
                .globalOperationParameters(aParameters)
                .forCodeGeneration(false)
                .select()
                .apis(RequestHandlerSelectors.basePackage("zx.privder.controller"))
                .paths(PathSelectors.any())
                .build();
    }


    /**
     * 構建 api文檔的詳細信息函數
     * @return
     */
    private ApiInfo zxApiInfo() {
        return new ApiInfoBuilder()
                .title("swagger-demo")
                .description("swagger- demo--創建於2018/4/02")
                .version("1.0")//版本
                .build();
    }
}
  • 測試 瀏覽器輸入(默認端口8080) http://localhost:8080/swagger-ui.html
    在這裏插入圖片描述

swagger常用註解

  • @Api 用在類上,類描述
  • @ApiOperation 用在方法上,方法描述
  • @ApiParam 用在方法參數上
  • @ApiModel 用在實體類,類解釋
  • @ApiModelProperty 用在實體字段,字段解釋

注:@Api裏的description已廢棄,現使用tags更好來分組,如果tags中的值設置爲中文, 那麼下面的方法名點擊將不能被展(英文沒這種問題),解決方法可以在swaggerConfig下配置tags或者升級版本

其他

  • swagger可以在配置類裏配置多個組
  • swagger-ui是通過獲取接口的json數據渲染頁面的,即通過swagger的註解將生成接口的描述服務,默認地址爲/v2/api-docs,如果需要改變這個請求地址,可以在properties中配置。例如:springfox.documentation.swagger.v2.path=/swagger。

swagger導出生成html
1)利用swagger2markup插件導出接口
2)使用asciidoctor插件配合swagger2markup生成html文件

		<!--swagger2markup插件-->
            <plugin>
                <groupId>io.github.swagger2markup</groupId>
                <artifactId>swagger2markup-maven-plugin</artifactId>
                <version>1.3.1</version>
                <configuration>
                    <!-- api-docs訪問url -->
                    <swaggerInput>http://localhost:8080/zx/swagger?group=zx</swaggerInput>
                    <!-- 生成爲單個文檔,輸出路徑
                    <outputFile>src/main/doc/api</outputFile>-->
                    <!-- 生成爲多個文檔,輸出路徑 -->
                    <outputDir>F:\download\swagger</outputDir>
                    <config>
                        <!-- wiki格式文檔 -->
                        <!--<swagger2markup.markupLanguage>CONFLUENCE_MARKUP</swagger2markup.markupLanguage> -->
                        <!-- ascii格式文檔 -->
                        <swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage>
                        <!-- markdown格式文檔 -->
                        <!--<swagger2markup.markupLanguage>MARKDOWN</swagger2markup.markupLanguage>-->
                        <swagger2markup.pathsGroupedBy>TAGS</swagger2markup.pathsGroupedBy>
                    </config>
                </configuration>
            </plugin>

            <!--asciidoctor插件-->
            <plugin>
                <groupId>org.asciidoctor</groupId>
                <artifactId>asciidoctor-maven-plugin</artifactId>
                <version>1.5.6</version>
                <configuration>
                    <sourceDirectory>F:\download\swagger</sourceDirectory>
                    <outputDirectory>F:\download\swagger\html</outputDirectory>
                    <backend>html</backend>
                    <sourceHighlighter>coderay</sourceHighlighter>
                    <attributes>
                        <toc>left</toc>
                    </attributes>
                </configuration>
            </plugin>       

springCloud集成swagger
springcloud 相當於多個springboot的合集,需要把所有的文檔放一起集中展示,在zuul下配置總入口即可。 注:分組的話需要配置分組信息,存於swagger.properties中 key爲serviceId,value爲分組名(多個用逗號隔開)
代碼如下

package zx.cn.zuul.configuration;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;

/**
 * 分佈式swagger文檔配置
 */
@Component
@Primary
@Slf4j
@EnableSwagger2
public class ZuulSwaggerConfig implements SwaggerResourcesProvider {
    /**版本**/
    private final String version = "2.0";
    @Autowired
    private ZuulProperties properties;
    /**
     * 構建文檔列表
     * @return
     */
    @Override
    public List<SwaggerResource> get() {
        //讀取屬性文件
        Properties p = readProperties();
        List<SwaggerResource> resources = Lists.newArrayList();
        properties.getRoutes().values().stream().forEach((route)->{
            String serviceId = route.getServiceId();
            String group_property = p.getProperty(serviceId);
            //分組
            if(StringUtils.isNotBlank(group_property)){
                String[] groupNames=group_property.split(",");
                for(String groupName:groupNames){
                    resources.add(createResource(serviceId,serviceId,version,groupName));
                }
            }else {//未分組
                resources.add(createResource(serviceId,serviceId,version));
            }
        });
        return resources;
    }

    /**
     * 構建SwaggerResource(不分組)
     * @param name
     * @param location
     * @param version
     * @return
     */
    private SwaggerResource createResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation("/" + location + "/v2/api-docs" );
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }

    /**
     * 構建SwaggerResource(分組)
     * @param name
     * @param location
     * @param version
     * @param groupName
     * @return
     */
    private SwaggerResource createResource(String name, String location, String version, String groupName) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation("/" + location + "/v2/api-docs?group=" + groupName);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }

    /**
     * 解析 swagger.properties
     * @return
     */
    private Properties readProperties() {
        Properties p = new Properties();
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(ZuulSwaggerConfig.class.getResourceAsStream("/swagger.properties"), "UTF-8");
            p.load(in);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("加載 swagger.properties 屬性文件出錯,錯誤信息:" + e.getMessage());
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return p;
    }

}

注: springcloud swagger 版本推薦2.7.0 及以上

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章