温馨提示×

Linux系统中Swagger的集成方法是什么

小樊
43
2025-11-02 01:47:40
栏目: 智能运维

1. 安装基础环境
在Linux系统上集成Swagger前,需根据技术栈安装对应基础环境:

  • Java环境(Java-based项目必需):Swagger依赖Java运行环境,通过以下命令安装OpenJDK 11(以Ubuntu为例):
    sudo apt update
    sudo apt install openjdk-11-jdk
    
    验证安装:java -version(需显示Java版本信息)。
  • Node.js与npm(Node.js项目必需):用于安装Swagger UI或Swagger Editor,安装命令:
    sudo apt update
    sudo apt install -y nodejs npm
    

2. Java-based项目(如Spring Boot/Spring MVC)集成步骤
若项目基于Spring框架,可通过Maven/Gradle添加Swagger依赖,并配置文档生成规则:

  • 配置构建工具依赖
    • Maven(pom.xml):添加springfox-swagger2springfox-swagger-ui依赖:
      <dependencies>
          <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>
      </dependencies>
      
    • Gradle(build.gradle):添加对应依赖:
      dependencies {
          implementation 'io.springfox:springfox-swagger2:2.9.2'
          implementation 'io.springfox:springfox-swagger-ui:2.9.2'
      }
      
  • 创建Swagger配置类:通过@EnableSwagger2注解启用Swagger,并配置API扫描范围(示例为Spring Boot配置类):
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.any()) // 扫描所有API接口
                    .paths(PathSelectors.any())         // 扫描所有路径
                    .build();
        }
    }
    
  • 启动应用并访问Swagger UI:启动Spring Boot应用后,在浏览器中访问http://localhost:8080/swagger-ui.html(端口根据实际调整),即可查看API文档并测试接口。

3. Node.js项目集成步骤
若项目基于Node.js,可通过npm安装Swagger工具,并配置Swagger文档:

  • 安装Swagger工具:全局安装swagger-ui-express(用于集成Swagger UI)和swagger-jsdoc(用于生成Swagger文档):
    sudo npm install -g swagger-ui-express swagger-jsdoc
    
  • 创建Swagger配置文件:新建swagger.json(或swagger.yaml),定义API元数据(示例):
    {
      "swagger": "2.0",
      "info": {
        "description": "Sample API Documentation",
        "version": "1.0.0",
        "title": "Sample API"
      },
      "basePath": "/api",
      "paths": {
        "/users": {
          "get": {
            "summary": "Get all users",
            "responses": {
              "200": {
                "description": "A list of users",
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/definitions/User"
                  }
                }
              }
            }
          }
        }
      },
      "definitions": {
        "User": {
          "type": "object",
          "properties": {
            "id": {
              "type": "integer"
            },
            "name": {
              "type": "string"
            }
          },
          "required": ["id", "name"]
        }
      }
    }
    
  • 集成Swagger UI到应用:在Node.js应用中引入Swagger UI,并指向配置文件(示例):
    const express = require('express');
    const swaggerUi = require('swagger-ui-express');
    const swaggerDocument = require('./swagger.json');
    const app = express();
    
    // 集成Swagger UI到/api-docs路径
    app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
    
    // 其他路由和中间件
    app.get('/api/users', (req, res) => {
      res.json([{ id: 1, name: 'John Doe' }]);
    });
    
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
      console.log(`Server running on port ${PORT}`);
    });
    
  • 启动应用并访问:运行node app.js后,访问http://localhost:3000/api-docs即可查看Swagger UI。

4. 使用Docker简化部署
若不想手动配置环境,可通过Docker快速部署Swagger Editor和Swagger UI:

  • 安装Docker:以Ubuntu为例,安装Docker并启动服务:
    sudo apt update
    sudo apt install docker.io
    sudo systemctl start docker
    sudo systemctl enable docker
    
  • 部署Swagger Editor:拉取镜像并运行容器(映射端口38080):
    docker pull swaggerapi/swagger-editor:v4.15.5
    docker run -d -p 38080:8080 swaggerapi/swagger-editor:v4.15.5
    
    访问http://localhost:38080即可使用Swagger Editor编写API文档。
  • 部署Swagger UI:拉取镜像并运行容器(映射端口38081):
    docker pull swaggerapi/swagger-ui:v4.15.5
    docker run -d -p 38081:8080 swaggerapi/swagger-ui:v4.15.5
    
    访问http://localhost:38081即可查看Swagger UI(需将url参数指向API文档地址,如http://your-server-ip:8080/swagger.json)。

5. 可选:配置Web服务器(Apache/Nginx)
若需将Swagger UI部署到生产环境,可通过Apache或Nginx反向代理提升访问安全性与性能:

  • Apache配置示例:创建虚拟主机配置文件/etc/apache2/sites-available/swagger.conf,内容如下:
    <VirtualHost *:80>
        ServerName your-domain.com
        DocumentRoot /var/www/html/swagger-ui
        <Directory /var/www/html/swagger-ui>
            Options Indexes FollowSymLinks
            AllowOverride All
            Require all granted
        </Directory>
    </VirtualHost>
    
    启用配置并重启Apache:
    sudo a2ensite swagger.conf
    sudo systemctl reload apache2
    
  • Nginx配置示例:创建服务器块配置文件/etc/nginx/sites-available/swagger,内容如下:
    server {
        listen 80;
        server_name your-domain.com;
        root /var/www/html/swagger-ui;
        index index.html;
    
        location / {
            try_files $uri $uri/ /index.html;
        }
    }
    
    启用配置并重启Nginx:
    sudo ln -s /etc/nginx/sites-available/swagger /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx
    

0