SpringBoot整合Swagger和Actuator

前言

本篇文章主要介紹的是SpringBoot整合Swagger(API文檔生成框架)和SpringBoot整合Actuator(項目監控)使用教程。html

SpringBoot整合Swagger

說明:若是想直接獲取工程那麼能夠直接跳到底部,經過連接下載工程代碼。java

Swagger 介紹

Swagger 是一套基於 OpenAPI 規範構建的開源工具,能夠幫助咱們設計、構建、記錄以及使用 Rest API。Swagger 主要包含了如下三個部分:git

  • Swagger Editor:基於瀏覽器的編輯器,咱們可使用它編寫咱們 OpenAPI 規範。
  • Swagger UI:它會將咱們編寫的 OpenAPI 規範呈現爲交互式的 API 文檔,後文我將使用瀏覽器來查看而且操做咱們的 Rest API。
  • Swagger Codegen:它能夠經過爲 OpenAPI(之前稱爲 Swagger)規範定義的任何 API 生成服務器存根和客戶端 SDK 來簡化構建過程。

Swagger優缺點

優勢

  • 易用性好,Swagger UI提供很好的API接口的UI界面,能夠很方面的進行API接口的調用。
  • 時效性和可維護性好,API文檔隨着代碼變動而變動。 Swagger是根據註解來生成文API檔的,咱們能夠在變動代碼的時候順便更改相應的註解便可。
  • 易於測試,能夠將文檔規範導入相關的工具(例如 SoapUI), 這些工具將會爲咱們自動地建立自動化測試。

缺點

  • 重複利用性差,由於Swagger畢竟是網頁打開,在進行接口測試的時候不少參數沒法進行保存,所以不易於重複利用。
  • 複雜的場景不易模擬,好比使用token鑑權的,可能每次都須要先模擬登陸,再來進行接口調用。

不過上述的這些缺點其實也無傷大雅,能夠配合Postman來一塊兒使用!
Postman能夠保存參數並持久化生成文件,也能夠在Header中保存Token信息,也能夠動態的生成數字簽名等等。
若是有興趣的話,能夠看看我以前寫的這篇文章。
地址: Postman使用教程github

Swagger 相關地址

  • Swagger官網:http://swagger.io
  • Swagger的GitHub地址:https://github.com/swagger-api

開發準備

環境要求web

JDK:1.8spring

SpringBoot:1.5.9.RELEASE數據庫

首先仍是Maven的相關依賴:api

pom.xml文件以下:瀏覽器

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
        <scope>test</scope>
    </dependency>
    
        <!-- swagger RESTful API -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.2.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.2.2</version>
    </dependency>
    
</dependencies>

注: Swagger的jar包既可原生的 Swagger的架包,也能夠選擇maven倉庫SpringBoot已經整合好的Swagger的架包。安全

application.properties的文件的配置和通常的SpringBoot項目同樣便可。

代碼編寫

SpringBoot使用Swagger其實很簡單,只須要在啓動的時候添加@EnableSwagger2註解開啓,而後再使用@Bean註解初始化一些相應的配置便可,好比編輯Swagger UI界面的信息,指定Swagger負責掃描的package等等。

Swagger代碼配置以下:

@Configuration
    @EnableSwagger2
    public class Swagger2 {
    
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.pancm"))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("Spring Boot中使用Swagger2構建RESTful APIs")
                    .description("測試")
                    .termsOfServiceUrl("http://www.panchengming.com/")
                    .contact("xuwujing")
                    .version("1.0")
                    .build();
        }
    
    }

由於Swagger主要是用於生成API文檔,所以這裏咱們能夠直接編寫控制層的相關代碼,忽略掉Service層和Dao層相關的代碼編寫。這裏咱們首先編寫一個實體類。

實體類

又是萬能的用戶表

public class User {
        
         private Long id;
    
         private String name;
         
        
         private Integer age;
         
        //getter 和 setter 略
        
    }

Controller 控制層

Swagger主要的使用就是在控制層這塊,它是經過一些註解來爲接口提供API文檔。下述的代碼中主要使用的註解爲這兩個@ApiOperation@ApiImplicitParam這兩個,@ApiOperation註解來給API增長說明並經過@ApiImplicitParams註解來給參數增長說明,其中 value 是標題,notes是詳細說明。

下列是Swagger的一些註解說明,更詳細的能夠查看官方的wiki文檔。

  • @Api:將類標記爲Swagger資源。
  • @ApiImplicitParam:表示API操做中的單個參數。
  • @ApiImplicitParams:一個包裝器,容許列出多個ApiImplicitParam對象。
  • @ApiModel:提供有關Swagger模型的其餘信息,好比描述POJO對象。
  • @ApiModelProperty: 添加和操做模型屬性的數據。
  • @ApiOperation: 描述針對特定路徑的操做或一般是HTTP方法。
  • @ApiParam: 爲操做參數添加其餘元數據。
  • @ApiResponse: 描述操做的可能響應。
  • @ApiResponses: 一個包裝器,容許列出多個ApiResponse對象。
  • @Authorization: 聲明要在資源或操做上使用的受權方案。
  • @AuthorizationScope: 描述OAuth2受權範圍。
  • @ResponseHeader: 表示能夠做爲響應的一部分提供的標頭。
  • @ApiProperty: 描述POJO對象中的屬性值。
  • @ApiError : 接口錯誤所返回的信息
  • ...

官方wiki文檔地址:
https://github.com/swagger-api/swagger-core/wiki/Swagger-2.X---Annotations

控制層代碼以下:

@RestController
    @RequestMapping(value = "/api")
    public class UserRestController {
        
        private  final Logger logger = LoggerFactory.getLogger(this.getClass());
        
    
        @ApiOperation(value="建立用戶", notes="根據User對象建立用戶")
        @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")
        @PostMapping("/user")
        public boolean insert(@RequestBody User user) {
            logger.info("開始新增用戶信息!請求參數:{}",user);
            return true;
        }
        
        @ApiOperation(value="更新用戶", notes="根據User對象更新用戶")
        @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")
        @PutMapping("/user")
        public boolean update(@RequestBody User user) {
            logger.info("開始更新用戶信息!請求參數:{}",user);
            return true;
        }
        
        @ApiOperation(value="刪除用戶", notes="根據User對象刪除用戶")
        @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")
        @DeleteMapping("/user")
        public boolean delete(@RequestBody User user)  {
            logger.info("開始刪除用戶信息!請求參數:{}",user);
            return true;
        }
        
    
        @ApiOperation(value="獲取用戶列表", notes="根據User對象查詢用戶信息")
        @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")
        @GetMapping("/user")
        public User findByUser(User user) {
            logger.info("開始查詢用戶列表,請求參數:{}",user);
            User user2 =new User();
            user2.setId(1L);
            user2.setAge(18);
            user2.setName("xuwujing");
            return user2;
        }
        
    }

App 入口

和普通的SpringBoot項目基本同樣。

代碼以下:

@SpringBootApplication
    public class SwaggerApplication  {
    
        private static final Logger logger = LoggerFactory.getLogger(SwaggerApplication.class);
    
        public static void main(String[] args) {
            SpringApplication.run(SwaggerApplication.class, args);
            logger.info("Swagger程序啓動成功!");
        }
    }

功能測試

咱們成功啓動該程序以後,在瀏覽器上輸入:http://localhost:8183/swagger-ui.html, 就能夠看到Swagger的界面了。

界面的示例圖以下:

因爲Swagger的操做主要是在界面操做,所以用圖片會更加有說服力。

使用GET請求測試示例圖以下:

SpringBoot整合Actuator

說明:若是想直接獲取工程那麼能夠直接跳到底部,經過連接下載工程代碼。

Actuator介紹

從本質上講,Actuator爲咱們的應用程序帶來了生產就緒功能。經過這種依賴關係監控咱們的應用程序,收集指標,瞭解流量或數據庫的狀態變得微不足道。這個庫的主要好處是咱們能夠得到生產級工具,而無需本身實際實現這些功能。Actuator主要用於公開有關正在運行的應用程序的運行信息 - 運行情況,指標,信息,轉儲,env等。它使用HTTP端點或JMX bean來使咱們可以與它進行交互。一旦這個依賴關係在類路徑上,就能夠開箱即用幾個端點。與大多數Spring模塊同樣,咱們能夠經過多種方式輕鬆配置或擴展它。

注意事項

Actuator的1.x版本和2.x版本差異很大,本文介紹的是1.x版本。

Actuator如今與技術無關,而在1.x中,它與MVC相關聯,所以與Servlet API相關聯。
在2.x中,Actuator定義了它的模型,可插拔和可擴展,而不依賴於MVC。所以,經過這個新模型,咱們能夠利用MVC和WebFlux做爲底層Web技術。
此外,能夠經過實施正確的適配器來添加即將到來的技術。
最後,JMX仍然支持在沒有任何其餘代碼的狀況下公開端點。

上述的說明參考Actuator官網。

官網地址:
https://www.baeldung.com/spring-boot-actuators

開發準備

環境要求

JDK:1.8

SpringBoot:1.5.9.RELEASE

首先仍是Maven的相關依賴:

pom.xml文件以下:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
        <scope>test</scope>
    </dependency>
</dependencies>

而後就是application.yml的文件配置,這裏的配置主要是指定監控的端口和路徑以及關閉安全認證等等。

application.yml:

server:
  port: 8181 
management:
  security:
    enabled: false 
  port: 8888 
  context-path: /monitor
 
endpoints:
  shutdown:
    enabled: true
    
info:
  app:
   name:springboot-actuator
   version:1.0

代碼編寫

其實這塊不須要代碼的編寫,由於它只須要你在項目中添加了該依賴並進行配置以後便可使用。這裏咱們在建立一個普通的SpringBoot項目而且添加了Actuator的相關依賴,而後經過調用Actuator提供的一些接口就能夠得知相關的信息。
這些接口的一些說明以下:

1./autoconfig 能夠獲得配置生效信息

  1. /configprops 能夠獲得屬性的內容和默認值
  2. /beans 可 以獲得bean的別名、類型、是否單例、類的地址、依賴等信息
  3. /dump 可 以獲得線程名、線程ID、線程的狀態、是否等待鎖資源等信息
  4. /env 能夠獲得環境變量、JVM 屬性、命令行參數、項目使用的jar包等信息
    5.1 /sun.boot.library.path 能夠獲得JDK安裝路徑
  5. /health 能夠獲得磁盤檢測和數據庫檢測等信息
  6. /mappings 能夠獲得所有的URI路徑,以及它們和控制器的映射關係
  7. /metrics 能夠獲得JVM內容使用、GC狀況、類加載信息
    8.1 /gc.* 能夠獲得GC相關信息
    8.2 /mem.* 能夠獲得內存信息 ...
  8. /info 能夠獲得自定義的配置信息
  9. /shutdown 能夠進行關閉程序 post請求
  10. /trace 能夠獲得所Web請求的詳細信息
    12 ....

更多的相關配置說明能夠查看官方文檔!
若是經過經過接口信息返回的數據進行查看不夠清晰明瞭的話,能夠結合SpringCloud Hystrix-Dashboard進行轉換圖表查看。
具體使用能夠參考: SpringCloud學習系列之三----- 斷路器(Hystrix)和斷路器監控(Dashboard) 這篇文章。

功能測試

咱們成功啓動該程序以後,便來進行測試。

首先查看啓動日誌,會發現啓動了兩個端口,一個是springboot項目自身的端口,還有一個Actuator監控的端口。

示例圖:

對外提供的Actuator主要是能夠幫助咱們獲取一些程序以及一些環境的相關信息。

好比獲取程序健康狀態。
在瀏覽器輸入:

http://localhost:8888/monitor/health

便可查看。

示例圖:

固然也能夠自定一些程序信息,好比定義程序版本。

在瀏覽器輸入:

http://localhost:8888/monitor/info

示例圖:

其它

項目地址

SpringBoot整合Swagger的項目工程地址:
https://github.com/xuwujing/springBoot-study/tree/master/springboot-swagger

SpringBoot整合Actuator的項目工程地址:
https://github.com/xuwujing/springBoot-study/tree/master/springboot-actuator

SpringBoot整個集合的地址:
https://github.com/xuwujing/springBoot-study

SpringBoot整合系列的文章

SpringBoot系列博客:

音樂推薦

原創不易,若是感受不錯,但願給個推薦!您的支持是我寫做的最大動力! 版權聲明: 做者:虛無境 博客園出處:http://www.cnblogs.com/xuwujing CSDN出處:http://blog.csdn.net/qazwsxpcm     我的博客出處:http://www.panchengming.com

相關文章
相關標籤/搜索