微服網關(Zuul)集成swagger統一模塊API文檔(2019.12.02)

微服網關集成swagger統一API文檔(使用swagger-bootstrap-ui界面)

使用swagger-bootstrap-ui 好處在於可以使用全局參數,例如請求頭,或者公共請求參數。

測試模塊改造: (例如當他是商城後臺管理模塊)

1. 加上swagger依賴:

	<!--springfox-swagger2依賴-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

2.Swagger2Config.java 配置類

import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * <p>
 * Swagger2 配置屬性
 * </p>
 * @description: Swagger2 配置類
 * @author: zhihao
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {
    
	/**
     * 創建RestApi 幷包掃描controller
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())// 對所有api進行監控
//                .apis(RequestHandlerSelectors.basePackage("com.xkcoding.swagger.controller")) 或者可以進行包掃描,單獨掃描一個包的接口監控
                .paths(PathSelectors.any())
            	 //不顯示錯誤的接口地址
                .paths(Predicates.not(PathSelectors.regex("/error.*")))//錯誤路徑不監控
                .build();
    }
    
	/**
     * 創建Swagger頁面 信息
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("spring-boot-demo")
                .description("當他是商城後臺管理模塊")
//                .contact(new Contact("zhihao", "****", "****"))
                .version("1.0.0-SNAPSHOT")
                .build();
    }

}

3. Controller接口:

@RestController
@Slf4j
@Api(tags = "用戶管理",description = "獲取用戶信息的")
public class TestController {


    @Autowired
    private  UserService userService;

    @Autowired
    private HttpServletRequest request;

    /**
     * 查詢全部封裝成爲一個List<map>
     * @return
     */
    @ApiOperation(value = "用戶查詢", notes = "接口描述",response = User.class)
    @ApiImplicitParams({@ApiImplicitParam(name = "username", value = "用戶名", dataType = "STRING", paramType = "QUERY", defaultValue = "默認值張韶涵",required = true)})
    @GetMapping("/findOneMap")
    public User findOneMap(String username){
        User user = userService.findOneMap(username);
        System.out.println(user);
        return user;
    }

4. User.java對象

@ApiModel(description = "用戶對象")
public class User  implements Serializable {
    // 主鍵
    private Long id;
    @ApiModelProperty(value = "用戶名字")
    private String username;
    @ApiModelProperty(value = "密碼")
    private String password;
    // 姓名
    private String name;
    //此處省略getter和setter方法 .. ..

5. 到此配置完畢,啓動項目訪問http://${host}:${port}/swagger-ui.html 是否能訪問到原生態的Ui頁面,能正常看到,就說明正常配置成功!

多個模塊都是按照上面那樣配置.然後在網關配置類的集合那加上swaggerResource(xxx,xxx,xxx);

微服網關模塊改造:

1. 在網關的模塊上加上swaggerswagger-bootstrap-ui依賴:

		<!--zuul依賴之前已有,下面加上依賴-->
		<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
        <!--springfox-swagger2依賴-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- swagger-bootstrap-ui包使用的是舊的,新的並不穩定,有問題 -->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>

2. 寫個配置類實現SwaggerResourcesProvider接口 (主要爲了獲取所有模塊的API資源)

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;

@Component //交給容器管理
@Primary  //代表是Swagger主 配置
@EnableSwagger2 //啓用Swagger2
public class DocumentationConfig implements SwaggerResourcesProvider {

/* @Autowired
    private RouteLocator routeLocator;*/
    
    @Override
    public List<SwaggerResource> get() {
//        								    /註冊的服務名/v2/xxxx 固定寫法
//resources.add(swaggerResource("客戶端", "/eureka-client/v2/api-docs", "2.0"));  
//resources.add(swaggerResource("測試端", "/eureka-test/v2/api-docs", "2.0"));
        List<SwaggerResource> resources = new ArrayList<>();
        //這我使用了網關轉發
        resources.add(swaggerResource("商城前臺管理", "/client/v2/api-docs", "1.0"));
        resources.add(swaggerResource("商城後臺管理", "/test/v2/api-docs", "1.0"));
        
		/* List<Route> routes = routeLocator.getRoutes(); 另一個方式: 遍歷所有註冊的服務添加進來
        System.out.println(routes.toString());
        for (Route route:routes) {
            resources.add(swaggerResource(route.getId(), route.getFullPath().replace("**", "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;
    }
}

3. 啓動網關模塊,訪問: http://${host}:${port}/doc.html 測試是否能看到模塊的接口! (如下圖)

擴展資料:

齊全的swagger註解介紹

knife4j是爲Java MVC框架集成Swagger生成Api文檔的增強解決方案,前身是swagger-bootstrap-ui

另外關於response屬性值

一般在完成以上情況後,字段說明都會顯示,這裏再提醒一下大家,如果已經在泛型中強制約束了返回類型後,就無需在註解@ApiOperation中設置response屬性值,比如如下代碼

@ApiOperation(value = "查詢所有",response=AlarmReponse.class)
@GetMapping("/queryAll")
public Rest<List<AlarmResponse>> queryAll(){
    //more..
}

以上代碼返回了泛型Rest類型的List-AlarmResponse集合,但是卻ApiOperation註解中加了response屬性爲AlarmResponse.class,這種情況會造成Ui只顯示AlarmReponse類的屬性說明,這顯然是不對的,因爲它把Rest的屬性給忽略了,所以:

一般情況下,是不寫註解@ApiOperation中的response屬性值,能少寫就少寫,將剩下的交給springfox-swagger這個框架,由它自動解析生成接口返回類型

最後貼一個簡單的返回封裝類供大家參考(Rest.java)

public class Rest<T> {

    @ApiModelProperty(value = "是否成功")
    private boolean success=true;
    @ApiModelProperty(value = "返回對象")
    private T data;
    @ApiModelProperty(value = "錯誤編號")
    private Integer errCode;
    @ApiModelProperty(value = "錯誤信息")
    private String message;
	.....省略set,get
}
發佈了29 篇原創文章 · 獲贊 3 · 訪問量 1602
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章