CentOS环境下Swagger的部署与实践案例分析
在CentOS上使用Swagger前,需安装必要的基础软件包,确保系统兼容性:
sudo yum update -y
sudo yum install -y java-1.8.0-openjdk-devel
sudo yum install -y maven
node -v
与npm -v
。Swagger UI是交互式API文档工具,以下是在CentOS上的部署步骤:
wget https://github.com/swagger-api/swagger-ui/archive/refs/tags/v3.34.0.tar.gz
tar -xzf v3.34.0.tar.gz
mv swagger-ui-3.34.0 /var/www/html/swagger-ui
httpd.conf
添加虚拟主机:<VirtualHost *:80>
ServerName your_server_ip
DocumentRoot /var/www/html/swagger-ui
<Directory /var/www/html/swagger-ui>
Require all granted
</Directory>
</VirtualHost>
重启Apache:sudo systemctl restart httpd
api.yaml
(符合OpenAPI规范),放置在Web目录下,内容示例如下:swagger: '2.0'
info:
title: Sample API
version: 1.0.0
paths:
/hello:
get:
summary: Say hello
responses:
'200':
description: Success
Alias /api-docs /var/www/html/swagger-ui/api.yaml
<Directory /var/www/html/swagger-ui>
Options Indexes FollowSymLinks
</Directory>
重启Apache后,访问http://your_server_ip/swagger-ui/index.html
即可查看并测试API。对于Java Spring Boot项目,可通过注解自动生成API文档:
pom.xml
中引入Swagger与Swagger UI依赖:<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>
SwaggerConfig
类,启用Swagger并定义文档范围:@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
@RestController
@Api(tags = {"用户管理"})
public class UserController {
@GetMapping("/users")
@ApiOperation(value = "获取用户列表", notes = "返回所有用户信息")
public List<User> getUsers() {
return userService.getAllUsers();
}
}
http://localhost:8080/swagger-ui.html
即可查看交互式API文档。Swagger的跨平台特性依赖于工具链的一致性与容器化技术:
docker run -d -p 80:8080 swaggerapi/swagger-ui
访问http://your_server_ip
即可查看Swagger UI,无需关心CentOS底层环境。swagger-codegen
或openapi-generator
工具,根据OpenAPI规范生成Java、Python等多语言客户端/服务端代码,适配不同平台。./config/api.yaml
),避免绝对路径导致的跨平台问题;配置文件中统一使用/
作为路径分隔符。为保障API文档与接口的安全性,需在CentOS上配置认证机制:
api.yaml
中定义安全方案:securityDefinitions:
BasicAuth:
type: basic
paths:
/secure:
get:
security:
- BasicAuth: []
auth_basic
模块启用HTTP Basic认证:location /api/ {
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://localhost:8080;
}
htpasswd
工具添加认证用户:sudo htpasswd -c /etc/nginx/.htpasswd admin
securityDefinitions:
OAuth2:
type: oauth2
flow: accessCode
authorizationUrl: https://auth-server/oauth/authorize
tokenUrl: https://auth-server/oauth/token
scopes:
read: Read access
write: Write access
paths:
/data:
get:
security:
- OAuth2: ["read"]
以上案例覆盖了CentOS环境下Swagger的常见使用场景,从基础部署到高级安全配置,均提供了可操作的步骤与示例,帮助开发者快速上手并实现高效的API文档管理。