SpringCloud Zuul網關整合Swagger

一、關於Swagger

Swagger能成爲最受歡迎的REST APIs文檔生成工具之一,有以下幾個原因:

  • Swagger 可以生成一個具有互動性的API控制檯,開發者可以用來快速學習和嘗試API。
  • Swagger 可以生成客戶端SDK代碼用於各種不同的平臺上的實現。
  • Swagger 文件可以在許多不同的平臺上從代碼註釋中自動生成。
  • Swagger 有一個強大的社區,裏面有許多強悍的貢獻者

二、該篇博客使用技術版本

springcloud:Dalston.SR5

springboot:1.5.9.RELEASE

springfox-swagger-ui:2.7.0

pringfox-swagger2:2.7.0

zuul-core:1.3.0


三、開發實現

1、在總依賴中添加swagger相關依賴(因爲多處地方會使用)

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

2、在網關服務下創建swagger

首先網關路由先配置好,如下

zuul:
  host:
    connect-timeout-millis: 3000
    socket-timeout-millis: 3000
  #路由規則
  routes:
    api-user:
      path: /api/user/**
      serviceId: wc-client-user
      #防止網關轉發請求後session失效
      sensitiveHeaders: "*"
    api-search:
      path: /api/search/**
      serviceId: wc-client-search
      sensitiveHeaders: "*"

這裏主要創建DocumentationConfig和SwaggerConfig,目錄如下

DocumentationConfig.java


/**
 * 資源文檔配置類
 */
@Component
@Primary
public class DocumentationConfig implements SwaggerResourcesProvider{

    @Override
    public List<SwaggerResource> get() {
        List resources = new ArrayList<>();
        resources.add(swaggerResource("搜索服務接口", "/api/search/v2/api-docs", "1.0"));// /api/search/是網關路由,/v2/api-docs是swagger中的
        resources.add(swaggerResource("用戶服務接口", "/api/user/v2/api-docs", "1.0"));
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }

}

 

SwaggerConfig.java

/**
 * swagger配置
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("WingCloud")
                .description("WingCloud")
                .termsOfServiceUrl("http://localhost:8080")//網關端口
                .version("1.0")
                .build();
    }

    @Bean
    UiConfiguration uiConfig() {
        return new UiConfiguration(null, "list", "alpha", "schema",
                UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, false, true, 60000L);
    }

}

 

3、在網關啓動類上加上@EnableSwagger2註解

4、在client服務內的controller中進行註明

筆者這裏以user服務爲例

如下在類上添加@Api,在方法上添加@ApiOperation,當然還有其他註解,讀者可自行百度/谷歌

/**
 * 用戶請求處理控制器
 */
@Api("用戶管理接口")
@RestController
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    /**
     * 用戶登錄
     * @param request
     * @param result
     * @param req
     * @return
     */
    @ApiOperation(value = "/login",notes = "登錄接口")
    @RequestMapping("/login")
    public SingleResult<TokenResponse> login(@Valid @RequestBody LoginRequest request, BindingResult result,HttpServletRequest req){
        //必須要調用validate方法才能實現輸入參數的合法性校驗
        System.out.println("-------------test-----------");
        validate(result);
        return userService.login(request,req);
    }
}

5、在client服務中添加Swagger配置

如下圖目錄

SwaggerConfig.java

/**
 * swagger配置
 */
@EnableSwagger2
@Configuration
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("top.wingcloud.controller"))//過濾的路徑
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("wc-client-user")
                .description("接口文檔說明")
                .contact(new Contact("淺然", "", "[email protected]"))
                .version("2.0")
                .build();
    }
}

ok,配置整合完成後,啓動相應的服務,然後進入http://localhost:8080/swagger-ui.html即可看到如下界面

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