轉自:https://www.cnblogs.com/Leo_wl/p/11106098.html
Swagger API文檔集中化注冊管理
接口文檔是前后端開發對接時很重要的一個組件。手動編寫接口文檔既費時,又存在文檔不能隨代碼及時更新的問題,因此產生了像swagger這樣的自動生成接口文檔的框架。swagger文檔一般是隨項目代碼生成與更新,訪問地址也是基於項目地址,因此對項目數不多的團隊還好。如果團隊的項目很多,比如采用微服務架構的團隊,動則幾十甚至上百個服務項目,那就意味着前端開發人員需要記住幾十甚至上百個swagger文檔地址,那就很不友好了。目前貌似還沒有較流行的API文檔集中化管理項目(也或者是我沒找到),因此花了點時間自己集成了一個,介紹如下。
1. swagger-bootstrap-ui項目
該項目是github上的一個開源項目(https://github.com/xiaoymin/swagger-bootstrap-ui ),對swagger ui做了增強,功能整體看起來要豐富一些。來看看效果,
該項目的調試url地址原本是基於自身服務的,我將它改為了注冊服務的url地址,以支持注冊服務的接口調試。調整后的源碼地址: https://github.com/ronwxy/swagger-bootstrap-ui
2. swagger api注冊服務
該項目集成了swagger-bootstrap-ui,並提供了swagger api注冊接口,接受所有提供了有效配置的服務項目注冊,讓注冊的服務在一個頁面上可統一查看,再也不用記太多文檔地址了。
啟動注冊服務后,訪問 http://localhost:11090/doc.html 打開文檔頁面。如上圖,可通過下拉列表來選擇不同項目,加載項目的接口文檔查看或調試。
項目地址: 關注本文最后二維碼公眾號,回復“swagger”獲取源碼地址 (一個不只有實戰干貨的技術公眾號,歡迎關注。如果覺得有用,不要吝嗇你的star,反正又不要錢,O(∩_∩)O)
3. 服務端配置
在業務服務端,需要提供一些配置。
首先,需要配置一些Bean,如下提供了一個配置類(這里只列出了主要部分,完整代碼參考: https://github.com/ronwxy/base-spring-boot)
public class Swagger2AutoConfiguration { @Bean public Docket restApi() { ParameterBuilder builder = new ParameterBuilder(); builder.name("x-auth-token").description("授權token") .modelRef(new ModelRef("string")) .parameterType("header") .required(false); return new Docket(DocumentationType.SWAGGER_2) .groupName(groupName) .select() .apis(RequestHandlerSelectors.basePackage(apisBasePackage)) .paths(PathSelectors.any()) .build() .globalOperationParameters(Collections.singletonList(builder.build())) .apiInfo(apiInfo()); } @Profile({"dev"}) @Bean public CommandLineRunner swaggerRegistar(ConfigurableApplicationContext context) { return new SwaggerInfoRegistar(context); } /** * use to register swagger api info url to swagger api registry; * * @author liubo */ public class SwaggerInfoRegistar implements CommandLineRunner { @Override public void run(String... args) throws Exception { String url = buildLocalSwaggerDocsUrl(); registerLocalSwaggerUrl(url); } /** * register the v2/api-docs url * * @param url */ private void registerLocalSwaggerUrl(String url) { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new FormHttpMessageConverter()); MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); body.add("project", getApiTitle()); body.add("url", url); ResponseEntity<Map> re = restTemplate.postForEntity(getSwaggerRegisterUrl(), body, Map.class); if (HttpStatus.OK.equals(re.getStatusCode())) { logger.info("swagger api registered success to {}", getSwaggerRegisterUrl()); } else { logger.warn("swagger api registered failed [{}]", re.getBody().get("msg")); } } } }
該類完成了swagger的基本配置,同時將swagger的/v2/api-docs地址注冊到了步驟2中介紹的注冊服務。
然后,因為要從注冊服務端調用該業務服務的接口進行調試,存在跨域,因此服務需要做跨域支持,配置文件中添加如下定義,
@Bean @ConditionalOnMissingBean(name = "corsFilterRegistrationBean") public FilterRegistrationBean corsFilterRegistrationBean() { UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource(); CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.applyPermitDefaultValues(); corsConfiguration.setAllowedMethods(Arrays.asList(CorsConfiguration.ALL)); corsConfiguration.addExposedHeader(HttpHeaders.DATE); corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration); CorsFilter corsFilter = new CorsFilter(corsConfigurationSource); FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(corsFilter); filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE); filterRegistrationBean.addUrlPatterns("/*"); return filterRegistrationBean; }
最后,在屬性配置文件application.yml中配置一些必要的屬性,
swagger: api-title: Demo標題 #會展示在下拉列表框中,一般寫項目名稱 api-description: Demo描述,集中注冊 group-name: Demo項目 apis-base-package: cn.jboost.springboot.swagger # API類所在包名 swagger-registry-path: http://localhost:11090/swagger/register #就是2中注冊服務的注冊接口地址
配置完后, 就可以像一般項目一樣編寫接口類,加swagger注解。項目啟動時, 會自動向注冊服務完成注冊,刷新注冊服務的文檔頁面即可在下拉列表看到。
4. 總結
本文介紹了一個基於swagger ui增強版項目swagger-bootstrap-ui的接口文檔集中化管理實現。采用該實現,將所有swagger在線接口文檔集中管理,有效提高前后端對接效率。