基於SpringCloud的Microservices架構實戰案例-在線API管理

simplemall項目前幾篇回顧:html

源碼地址:https://github.com/backkoms/simplemallgithub

前端和後端的惟一聯繫,變成了API接口;API文檔變成了先後端開發人員聯繫的紐帶,變得愈來愈重要,swagger就是一款讓你更好的書寫API文檔的框架。 本實戰案例中也引入swagger2做爲API管理工具,下面羅列下swagger2+SpringBoot使用步驟。web

SpringBoot集成Swagger2

第一步,pom配置spring

  1. <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->apache

  2. <dependency>後端

  3.    <groupId>io.springfox</groupId>api

  4.    <artifactId>springfox-swagger2</artifactId>

  5.    <version>2.6.1</version>

  6. </dependency>

  7.  

  8. <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->

  9. <dependency>

  10.    <groupId>io.springfox</groupId>

  11.    <artifactId>springfox-swagger-ui</artifactId>

  12.    <version>2.6.1</version>

  13. </dependency>

第二步編寫配置管理類Swagger2Config

  1. package com.simplemall.micro.serv.page;

  2.  

  3. import org.springframework.context.annotation.Bean;

  4. import org.springframework.context.annotation.Configuration;

  5.  

  6. import io.swagger.annotations.ApiOperation;

  7. import springfox.documentation.builders.ApiInfoBuilder;

  8. import springfox.documentation.builders.PathSelectors;

  9. import springfox.documentation.builders.RequestHandlerSelectors;

  10. import springfox.documentation.service.ApiInfo;

  11. import springfox.documentation.spi.DocumentationType;

  12. import springfox.documentation.spring.web.plugins.Docket;

  13. import springfox.documentation.swagger2.annotations.EnableSwagger2;

  14.  

  15. /**

  16. * swagger2 configuration

  17. *

  18. * @author guooo

  19. *

  20. */

  21. @Configuration//SpringBoot啓動時自動裝載

  22. @EnableSwagger2//打開swagger2功能,缺失的話一樣沒法打開ui頁面

  23. publicclassSwagger2Config{

  24.  

  25.    @Bean

  26.    publicDocket createRestApi(){

  27.        returnnewDocket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()

  28.                .apis(RequestHandlerSelectors.basePackage("com.simplemall.micro.serv.page.api"))

  29.                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))

  30.                .paths(PathSelectors.any())

  31.                .build();

  32.    }

  33.  

  34.    privateApiInfo apiInfo(){

  35.        returnnewApiInfoBuilder().title("Front app Swagger apis").description("For micro-service 's app to use")

  36.                .version("V1.0").build();

  37.    }

  38. }

通過以上兩步簡單的配置後,能夠直接進行接口代碼的編寫。

  1. @Api(value ="用戶服務", tags ="用戶服務接口")

  2. @RestController

  3. @RefreshScope// 使用該註解的類,會在接到SpringCloud配置中心配置刷新的時候,自動將新的配置更新到該類對應的字段中。須要從新觸發加載動做可使用POST方式請求/refresh接口,該接口位於spring-boot-starter-actuator依賴,調用前需添加不然404。

  4. publicclassAPIAccountController{

  5.  

  6.    @ApiOperation(value ="用戶登錄")

  7.    @RequestMapping(value ="acc/login", method ={RequestMethod.POST })

  8.    publicRestAPIResult<String> login(@ApiParam(value ="手機號")@RequestParam(required =true)String phone,

  9.            @ApiParam(value ="密碼")@RequestParam(required =true)String password,HttpSession session){

  10.        RestAPIResult<String> restAPIResult =newRestAPIResult<>();

  11.        Account account = accountFeignClient.login(phone, password);

  12.    }

使用swagger進行API管理的話,對代碼有必定的侵入性,這個須要考慮在內。以前也提到過幾種在線API的管理方式,點擊連接《介紹幾款經常使用的在線API管理工具

使用SpringBoot技術,再以maven原始的方式引入swagger使用的話,遠不如一個starter來的爽,這裏介紹一個swagger-starter,能夠更快捷的與spring boot集成使用。

swagger-spring-boot-starter應用

在pom.xml中引入依賴:【當前最新版本 1.7.0.RELEASE】

  1. <dependency>

  2.    <groupId>com.spring4all</groupId>

  3.    <artifactId>swagger-spring-boot-starter</artifactId>

  4.    <version>1.7.0.RELEASE</version>

  5. </dependency>

注意:從1.6.0開始,咱們按Spring Boot官方建議修改了artifactId爲swagger-spring-boot-starter,1.6.0以前的版本不作修改,依然爲使用spring-boot-starter-swagger !

在應用主類中增長@EnableSwagger2Doc註解

  1. @EnableSwagger2Doc

  2. @SpringBootApplication

  3. publicclassBootstrap{

  4.  

  5.    publicstaticvoid main(String[] args){

  6.        SpringApplication.run(Bootstrap.class, args);

  7.    }

  8.  

  9. }

默認狀況下就能產生全部當前Spring MVC加載的請求映射文檔。

參數配置,配置示例

  1. swagger.enabled=true

  2.  

  3. swagger.title=spring-boot-starter-swagger

  4. swagger.description=Starterfor swagger 2.x

  5. swagger.version=1.4.0.RELEASE

  6. swagger.license=ApacheLicense,Version2.0

  7. swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html

  8.  

  9. swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger

  10.  

  11. swagger.contact.name=didi

  12. swagger.contact.url=http://blog.didispace.com

  13.  

  14. swagger.contact.email=dyc87112@qq.com

  15. swagger.base-package=com.didispace

  16. swagger.base-path=/**

  17. swagger.exclude-path=/error, /ops/**

  18.  

  19. swagger.globalOperationParameters[0].name=name one

  20. swagger.globalOperationParameters[0].description=some description one

  21. swagger.globalOperationParameters[0].modelRef=string

  22. swagger.globalOperationParameters[0].parameterType=header

  23. swagger.globalOperationParameters[0].required=true

  24. swagger.globalOperationParameters[1].name=name two

  25. swagger.globalOperationParameters[1].description=some description two

  26. swagger.globalOperationParameters[1].modelRef=string

  27. swagger.globalOperationParameters[1].parameterType=body

  28. swagger.globalOperationParameters[1].required=false

  29.  

  30. // 取消使用默認預約義的響應消息,並使用自定義響應消息

  31. swagger.apply-default-response-messages=false

  32. swagger.global-response-message.get[0].code=401

  33. swagger.global-response-message.get[0].message=401get

  34. swagger.global-response-message.get[1].code=500

  35. swagger.global-response-message.get[1].message=500get

  36. swagger.global-response-message.get[1].modelRef=ERROR

  37. swagger.global-response-message.post[0].code=500

  38. swagger.global-response-message.post[0].message=500post

  39. swagger.global-response-message.post[0].modelRef=ERROR

詳細介紹可參考源碼,地址:https://github.com/SpringForAll/spring-boot-starter-swagger。因爲JDK代碼編譯版本的限制,JDK1.7是不支持的,可以使用1.8

擴展閱讀:

 

相關文章
相關標籤/搜索