原文地址:https://dzone.com/articles/auto-publishing-amp-monitoring-apis-with-spring-bo

If you are heading down the path of a microservices style of architecture, one tenant that you will need to embrace is automation. Many moving parts are introduced with this style of architecture. If successful, your environment will have a plethora of service APIs available that the enterprise can consume for application development and integration.

This means that there must be a way that available API documentation can be discovered. API information needs to be effectively communicated throughout the enterprise that shows where APIs are used, how often APIs are used, and when APIs change. Not having this type of monitoring in place will hinder and possibly cripple the agility benefits that a microservice style of architecture can bring to the enterprise.

Spring Boot by Pivotal has led the way in providing a path to develop Microservices-based, cloud-ready applications in an Agile and minimal coding manner. If you want to find out more about Spring Boot, check out this blog by Matt McCandless. It doesn’t take much effort to implement a RESTful API for a service with Spring Boot. And, putting that service in a Microservices infrastructure does not take much effort either. (See our newest white paper for more.)

This blog will describe how Swagger/OpenAPI documentation can be applied to a Spring Boot implementation. We will show how API documentation and monitoring can be automatically published to an API documentation portal.

As an example, we introduce a reference Spring Boot API CRUD application (using Spring MVC/Data with Spring Fox) and set up the automatic publishing of API documentation and statistics to documentation portal GrokOla. In the example, we introduce two open-source utilities to help and allow published APIs the ability to be searched and notify users when changed.

Configuring Swagger in Spring Boot With Spring Fox

OpenAPI (fka Swagger) is an API documentation specification that allows RESTful APIs to be gleaned from code implementations. This is arguably more efficient than having to document APIs in a separate step.

Spring Fox is a framework that automates the generation of Swagger JSON documentation from Spring Boot applications. To see how easy it is to produce Swagger JSON documentation from a Spring Boot application, consider this simple Employee API Service application that implements a CRUD API for employees.

The employee CRUD API implementation can be found at this public GitHub repository.

The example application implements the following APIs using Spring MVC, Spring Data mapping to an Employee object model using Hibernate that is configured for an in-memory database.

When started, Employee objects can be created, read, updated, and deleted with the following APIs defined in the partial khs.exmaple.api.Api Spring REST controller implementation shown below.

 
  1. @RestController
 
  1. @RequestMapping("/api")
 
  1. public class Api {
 
 
  1. @Autowired
 
  1. EmployeeService service;
 
 
  1. @RequestMapping(method = RequestMethod.GET, value = "/employees/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
 
  1. ResponseEntity<Employee> employee(@PathVariable("id") Long id) {
 
  1. Employee employee = service.findEmployee(id);
 
  1. return new ResponseEntity<Employee>(employee, HttpStatus.OK);
 
  1. }
 
 
  1. @ApiOperation("value")
 
  1. @RequestMapping(method = RequestMethod.GET, value = "/employees", produces = MediaType.APPLICATION_JSON_VALUE)
 
  1. ResponseEntity<Iterable<Employee>> employees() {
 
  1. Iterable<Employee> employees = service.all();
 
  1. return new ResponseEntity<Iterable<Employee>>(employees, HttpStatus.OK);
 
  1. }
 
 
  1. ……..
 

Swagger documentation can be produced using the Spring Fox framework. Here is how it is applied to the example application.

Add the Spring Fox/Swagger Maven dependency to your project:

 
  1. <dependency>
 
  1. <groupId>io.springfox</groupId>
 
  1. <artifactId>springfox-swagger2</artifactId>
 
  1. <version>2.6.1</version>
 
  1. </dependency>
 

Then, a Spring Fox config is defined in a SwaggerConfig.java class along with the @EnableSwagger2 annotation:

 
  1. @Configuration
 
  1. @EnableSwagger2
 
  1. public class SwaggerConfig {
 
 
  1. @Bean
 
  1. public Docket apiDocket() {
 
  1. return new Docket(DocumentationType.SWAGGER_2)
 
  1. .apiInfo(apiInfo())
 
  1. .select()
 
  1. .paths(regex("/api.*"))
 
  1. .build();
 
  1. }
 
 
  1. private ApiInfo apiInfo() {
 
  1. return new ApiInfoBuilder()
 
  1. .title("Employee API Example")
 
  1. .description("A implementation of an API Gateway for Keyhole Labs Microservice Reference.")
 
  1. .contact(new Contact("Keyhole Software", "keyholesoftware.com", "asktheteam@keyholesoftware.com"))
 
  1. .version("2.0")
 
  1. .build();
 
  1. }
 
  1. }
 

Once configured and once the application has started, Swagger JSON documentation can be obtained with http://127.0.0.1:8080/v2/api-docs.

Automated API Publishing

Making Swagger API JSON available for teams to consume essential for success, especially if you are trying to eliminate agility-hindering silos and creating an organization with cross-functional teams (i.e., “inverting” Conway’s Law).

The Swagger framework can produce human-readable HTML Swagger documentation. However, it is not indexable/searchable, aggregated with other APIs, and does not allow additional documentation to be added. A better mechanism is required.

Ideally, this will be a developer API portal that will aggregate available APIs for an organization, index APIs for searchability, allow developers to easily add additional documentation, and provide usage metrics and notifications when APIs change.

Automating this step is essential for acceptance and providing value. Our developers at Keyhole Software have created an open source Spring Boot starter framework that will publish Swagger to a portal every time the application is started.

@PublishSwagger

Once you have Spring Fox and Swagger enabled, you can apply this starter framework with the following steps.

Add the following dependency to your pom.xml:

 
  1. <dependency>
 
  1. <groupId>com.keyholesoftware</groupId>
 
  1. <artifactId>khs-spring-boot-publish-swagger-starter</artifactId>
 
  1. <version>1.0.0</version>
 
  1. </dependency>
 

Add the following properties your application.yml file:

 
  1. swagger:
 
  1. publish:
 
  1. publish-url: https://demo.grokola.com/swagger/publish/14
 
  1. security-token: 6e8f1cc6-3c53-4ebe-b496-53f19fb7e10e
 
  1. swagger-url: http://127.0.0.1:${server.port}/v2/api-docs
 

Note: This config is pointing to the GrokOla Demo API Wiki Portal.

Add the @PublishSwagger annotation to your Spring Boot startup class.

 
  1. @SpringBootApplication
 
  1. @PublishSwagger
 
  1. public class EmployeesApp {
 
  1. public static void main(String[] args) {
 
  1. SpringApplication.run(EmployeesApp.class, args);
 
  1. }
 
  1. }
 

When the application is started, Swagger JSON will be published to the specified publish-url. In this case, it is Keyhole’s GrokOla API wiki portal software demo site.

Here is the imported API in GrokOla:

GrokOla is a wiki that allows APIs to be imported manually and in a headless, automated manner. This blog shows how you can easily publish your APIs using Spring Boot. However, with GrokOla, you can also manually import Swagger APIs.

You can obtain a demo user ID at this link. The example in this blog is already configured to point to this demo site. So, if you have an idea, you can play around with the API wiki portal.

@EnableApiStats

Just having readily available API documentation is not enough to govern your APIs. Seeing who, how, and when they are used is critical. There are tools and sniffers that you can use to route and filter network activity, but this is a separate piece of software deployed to a location that has to be configured, typically by operations personnel and not the developer.

A more succinct and easy-to-apply mechanism has be created for Spring Boot developers to obtain and emit individual application API usage statistics to a portal for analysis. This has been implemented as another Spring Boot starter (public, open source) framework available on GitHub.

This solution applied in the following three easy steps.

    1. Add the following dependency to your POM.XML:

 
  1. <dependency>
 
  1. <groupId>com.keyholesoftware</groupId>
 
  1. <artifactId>khs-spring-boot-api-statistics-starter</artifactId>
 
  1. <version>1.0.1</version>
 
  1. </dependency>
 
    1. Add the configuration below to your application.yml. This will emit an API’s stats to the GrokOla demo instance.

 
  1. api:
 
  1. statistics:
 
  1. name: employeeapi
 
  1. pattern-match: /api/.*
 
  1. publish-url: https://demo.grokola.com/sherpa/api/stats/41
 
  1. token: 6e8f1cc6-3c53-4ebe-b496-53f19fb7e10e
 
  1. Add the @EnableApiStatistics to your application boot main class implementation:

 
  1. @SpringBootApplication
 
  1. @PublishSwagger
 
  1. @EnableApiStatistics
 
  1. public class EmployeesApp {
 
 
  1. public static void main(String[] args) {
 
  1. SpringApplication.run(EmployeesApp.class, args);
 
  1. }
 
  1. }
 

When the application starts, after every ten requests against the API, collected usage stats will be emitted to the publish-url. The number of requests before emission to the URL is configurable. This is done on a separate thread as not to inhibit performance.

Here is the console of the example application after ten API requests:

Notice, the API JSON being sent to the published URL.

GrokOla has been outfitted to accept the emitted API JSON stream and provide usage statistics to the user by associating API usage with published. This is accessible from the API documentation section of GrokOla. A screenshot for this API stats view is shown below.

The Usage view shows API routes type counts total duration and average duration. This allows developers to determine what and how long their APIs are being used. You can also view popularity and where and when APIs are being used.

Final Thoughts

Automatically publishing your API documentation in a seamless manner and providing a way to monitor their usage behavior is critical to the success of your services-based platform.

Having automated API publishing and monitoring will strengthen a microservices style of architecture and bring agility to the enterprise. Available API documentation should be easily discoverable, with information effectively communicated throughout the enterprise dictating where APIs are used, how often APIs are used, and when APIs change.

We have released two open-source utilities that should help in this goal:

  1. Spring Boot Starter for publishing Swagger/OpenAPI to a portal every time the application is started.

    • This Spring Boot starter can be used to POST Swagger JSON to a publishing target (URL) upon startup of the Spring Boot application. The body of the request will be the raw Swagger JSON, and a security token can be applied to ensure that only authorized clients have access.
  2. Spring Boot Starter for publishing individual application API usage statistics to a portal for analysis.
    • This Spring Boot starter can be used to POST API usage statistics to a publishing target (URL) on a configurable interval. The body of the request will be a JSON array of statistics, and a security token can be applied to ensure that only authorized clients have access.

We hope that you find this helpful!

Auto-Publishing and Monitoring APIs With Spring Boot--转的更多相关文章

  1. Java | Spring Boot Swagger2 集成REST ful API 生成接口文档

      Spring Boot Swagger2 集成REST ful API 生成接口文档 原文 简介 由于Spring Boot 的特性,用来开发 REST ful 变得非常容易,并且结合 Swagg ...

  2. 使用Spring Boot Actuator、Jolokia和Grafana实现准实时监控

    由于最近在做监控方面的工作,因此也读了不少相关的经验分享.其中有这样一篇文章总结了一些基于Spring Boot的监控方案,因此翻译了一下,希望可以对大家有所帮助. 原文:Near real-time ...

  3. spring boot整合Swagger2

    Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化RESTful风格的 Web 服务.总体目标是使客户端和文件系统作为服务器以同样的速度来更新.文件的方法,参数和模型紧密集成到服务器 ...

  4. 使用Spring Boot Actuator、Jolokia和Grafana实现准实时监控--转

    原文地址:http://mp.weixin.qq.com/s?__biz=MzAxODcyNjEzNQ==&mid=2247483789&idx=1&sn=ae11f04780 ...

  5. Spring Boot 入门系列(二十二)使用Swagger2构建 RESTful API文档

    前面介绍了如何Spring Boot 快速打造Restful API 接口,也介绍了如何优雅的实现 Api 版本控制,不清楚的可以看我之前的文章:https://www.cnblogs.com/zha ...

  6. Spring Boot中使用Swagger2构建RESTful APIs

    关于 Swagger Swagger能成为最受欢迎的REST APIs文档生成工具之一,有以下几个原因: Swagger 可以生成一个具有互动性的API控制台,开发者可以用来快速学习和尝试API. S ...

  7. Spring Boot中使用Swagger2构建RESTful APIs介绍

    1.添加相关依赖 <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 --> <depen ...

  8. spring boot 四大组件之Auto Configuration

    SpringBoot 自动配置主要通过 @EnableAutoConfiguration, @Conditional, @EnableConfigurationProperties 或者 @Confi ...

  9. Spring Boot Reference Guide

    Spring Boot Reference Guide Authors Phillip Webb, Dave Syer, Josh Long, Stéphane Nicoll, Rob Winch,  ...

随机推荐

  1. Cocos2d-x 3.0多线程异步资源载入

    Cocos2d-x从2.x版本号到上周刚刚才公布的Cocos2d-x 3.0 Final版,其引擎驱动核心依然是一个单线程的"死循环".一旦某一帧遇到了"大活儿" ...

  2. 程序猿的量化交易之路(21)--Cointrader之Currency货币实体(9)

    转载须注明出自:http://blog.csdn.net/minimicall? viewmode=contents,http://cloudtrader.top 货币,Cointrader中基本实体 ...

  3. [JZOJ 5908] [NOIP2018模拟10.16] 开荒(kaihuang)解题报告 (树状数组+思维)

    题目链接: https://jzoj.net/senior/#contest/show/2529/1 题目: 题目背景:尊者神高达作为一个萌新,在升级路上死亡无数次后被一只大黄叽带回了师门.他加入师门 ...

  4. echarts中国地图

    echarts中国地图效果图: =================== 需要引入echarts的js文件:(1.echarts.min.js:2.china.js) 下载地址: echarts.min ...

  5. C# 导出excel的压缩包到浏览器页面

    需求背景:TCX_1710项目产品质量导出功能,客户希望每个总成导出到一个Excel表中 实现分析:客户选择时间段,点击导出按钮,默认导出开始时间当天的数据,每个总成一个Excel,将各个Excel打 ...

  6. Debian/Linux 下无线网卡驱动的安装

    我的 PC 型号是 Acer V3-572G, 安装了 Debian 后, 发现只能通过有线网络上网, 无法识别无线网卡, 以下是解决的过程(不局限于此型号 PC): 在命令行键入 lspci , 得 ...

  7. HDU 1548 A strange lift【BFS】

    题意:给出一个电梯,给出它的层数f,给出起点s,终点g,以及在每一层能够上或者下w[i]层,问至少需要按多少次按钮到达终点. 和POJ catch that cow一样,直接用了那一题的代码,发现一直 ...

  8. 前端学习之路——Git篇

    本文只是一个个人学习Git的笔记,如有错误的地方,还望指出,谢谢!参考资料如下: <Git教程--廖雪峰的官方网站 > bootstrap里面的--git_guide Git安装 在网上搜 ...

  9. 在javascript中对于this指向的再次理解

    总所周知,function () {}函数体内的this对象指向的是调用该函数的对象,那么我们看一下这个例子 <script> var length = 3; function fn () ...

  10. React 第三天

    第三天 01:在组件中使用style行内对象并封装样式对象: CmtItem.jsx: import React from 'react' //第一层封装 将样式对象和UI结构分离 // const ...