在Linux上搭建Swagger服务,通常是指使用Swagger UI来展示和测试RESTful API。以下是使用Docker和Swagger UI来搭建Swagger服务的步骤:
-
安装Docker: 如果你的Linux系统还没有安装Docker,请先安装它。以下是在基于Debian的系统(如Ubuntu)上安装Docker的命令:
sudo apt update sudo apt install docker.io对于基于Red Hat的系统(如CentOS),可以使用以下命令:
sudo yum install docker安装完成后,启动Docker服务并设置开机自启:
sudo systemctl start docker sudo systemctl enable docker -
拉取Swagger UI镜像: Docker Hub上有官方的Swagger UI镜像,你可以直接拉取下来使用:
docker pull swaggerapi/swagger-ui -
运行Swagger UI容器: 使用Docker运行Swagger UI容器,并将你的API文档挂载到容器中。假设你的API文档是一个JSON文件,名为
swagger.json,并且位于当前目录下:docker run -p 8080:8080 -v $(pwd)/swagger.json:/usr/src/app/swagger.json swaggerapi/swagger-ui这个命令会启动一个容器,并将容器的8080端口映射到宿主机的8080端口。同时,它会将本地的
swagger.json文件挂载到容器的/usr/src/app/swagger.json路径。 -
访问Swagger UI: 打开浏览器,访问
http://localhost:8080,你应该能够看到Swagger UI界面,并且能够加载和测试你的API。
如果你想要更深入地集成Swagger到你的应用程序中,你可能需要使用Swagger Codegen或者直接在你的代码中使用Swagger注解来生成API文档。这通常涉及到在你的项目中添加依赖,并配置Swagger工具来扫描你的代码库生成文档。
例如,如果你使用的是Spring Boot,你可以添加以下依赖到你的pom.xml文件中:
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>2.9.2version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>2.9.2version>
dependency>
然后,你需要配置Swagger,创建一个配置类,如下所示:
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;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build();
}
}
这样,当你启动你的Spring Boot应用程序时,Swagger UI将会自动集成,并可以通过http://localhost:8080/swagger-ui.html访问。
以上就是关于“如何在Linux上搭建Swagger服务”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm