温馨提示×

Swagger UI在Linux上如何配置

小樊
44
2025-04-21 05:22:35
栏目: 智能运维

在Linux上配置Swagger UI可以通过多种方法实现,以下是几种常见的方法:

使用Docker容器部署Swagger UI和Swagger Editor

  1. 安装Docker: 如果你还没有安装Docker,可以使用以下命令安装:

    sudo apt update
    sudo apt install -y docker.io
    sudo systemctl start docker
    sudo systemctl enable docker
    
  2. 拉取Swagger UI和Swagger Editor镜像

    docker pull swaggerapi/swagger-ui:latest
    docker pull swaggerapi/swagger-editor:latest
    
  3. 运行Swagger UI和Swagger Editor容器

    docker run -d -p 8080:8080 swaggerapi/swagger-ui:latest
    docker run -d -p 8081:8080 swaggerapi/swagger-editor:latest
    
  4. 访问Swagger UI和Swagger Editor

使用npm安装Swagger UI和Swagger Editor

  1. 安装Node.js和npm

    curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -
    sudo apt-get install -y nodejs
    
  2. 安装Express和http-server

    npm install -g express http-server
    
  3. 安装Swagger UI

    git clone https://github.com/swagger-api/swagger-ui.git
    cd swagger-ui
    npm install
    
  4. 安装Swagger Editor

    git clone https://github.com/swagger-api/swagger-editor.git
    cd swagger-editor
    npm install
    
  5. 启动Swagger UI和Swagger Editor

    • Swagger UI:
      http-server -p 8080
      
    • Swagger Editor:
      node index.js
      
  6. 访问Swagger UI和Swagger Editor

Spring Boot集成Swagger

  1. 添加Maven依赖

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>swagger-bootstrap-ui</artifactId>
        <version>1.9.6</version>
    </dependency>
    
  2. 配置Swagger

    @Configuration
    @EnableSwagger2
    @EnableSwaggerBootstrapUI
    public class SwaggerConfig {
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("swagger-bootstrap-ui RESTful APIs")
                    .description("swagger-bootstrap-ui")
                    .termsOfServiceUrl("http://localhost:5050/")
                    .contact("developer@mail.com")
                    .version("1.0")
                    .build();
        }
    }
    
  3. 启动项目: 启动项目后,访问 http://ip:port/doc.html 即可查看Swagger UI。

以上方法可以帮助你在Linux系统上成功配置Swagger UI,选择适合你项目需求的方法进行操作即可。

0