在Linux系统上使用Swagger监控API前,需先安装以下工具:
sudo apt update && sudo apt install -y nodejs npm
npm install -g http-server swagger-ui
docker pull swaggerapi/swagger-editor
docker pull swaggerapi/swagger-ui
docker run -d -p 38080:8080 swaggerapi/swagger-editor # Swagger Editor
docker run -d -p 38081:8080 swaggerapi/swagger-ui # Swagger UI
Swagger监控的前提是生成规范的API文档,常见方式有两种:
swagger.yaml
或swagger.json
文件,定义API的基本信息(如标题、版本)、路径(如/users
)、参数(如id
)、响应(如200
状态码)等。示例如下:swagger: '2.0'
info:
title: Linux API监控示例
version: 1.0.0
paths:
/users/{id}:
get:
summary: 获取用户信息
parameters:
- name: id
in: path
required: true
type: integer
responses:
'200':
description: 成功返回用户信息
<!-- pom.xml添加依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
// Swagger配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
cd swagger-editor-3.16.1
./node_modules/.bin/http-server -p 8080
访问http://<服务器IP>:8080
即可在线编辑Swagger文档。swagger.yaml
)复制到public
目录,启动服务:cd swagger-ui-3.48.0
./node_modules/.bin/http-server -p 8081
访问http://<服务器IP>:8081
,在界面中导入Swagger文档即可查看API详情。Swagger UI提供了交互式测试功能,可用于初步监控API状态:
/users/{id}
)。id: 1
),点击“Execute”发送请求。200
且返回预期数据,则说明API正常;若状态码为500
,则需排查后端问题。若需长期监控API性能、可用性,可集成以下工具:
prometheus.yml
,添加Swagger UI的监控目标:scrape_configs:
- job_name: 'swagger'
static_configs:
- targets: ['localhost:8081'] # Swagger UI的服务地址
grafana.ini
中设置url = http://localhost:9090
)。/var/log/swagger-ui/*.log
)发送到Elasticsearch,通过Kibana分析API调用趋势、错误率等。logrotate
管理Swagger日志,避免日志文件过大。示例如下(/etc/logrotate.d/swagger-editor
):/var/log/swagger-editor/*.log {
daily
missingok
rotate 7
compress
delaycompress
notifempty
create 0644 root root
}
journalctl
查看日志:journalctl -u swagger-editor -f # 实时查看日志
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/swagger-ui/**").authenticated()
.and()
.httpBasic();
}
通过以上步骤,可在Linux系统上利用Swagger实现API的文档管理、交互式测试、高级监控,提升API的可维护性与可靠性。