本文介紹在Linux系統中部署Swagger的步驟。Swagger是一個基于Java的API文檔生成工具,其部署需要Java環境以及maven或gradle構建工具。
一、Java環境安裝
Swagger依賴Java運行環境。使用OpenJDK或oracle JDK均可。以下命令以OpenJDK 11為例:
sudo apt update sudo apt install openjdk-11-jdk
二、Maven或Gradle配置
使用Maven或Gradle構建項目時,需在項目配置文件中添加Swagger依賴。
2.1 Maven (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>
2.2 Gradle (build.gradle):
dependencies { implementation 'io.springfox:springfox-swagger2:2.9.2' implementation 'io.springfox:springfox-swagger-ui:2.9.2' }
三、Swagger配置
創建一個Swagger配置類,啟用Swagger文檔生成。以下示例適用于spring boot和Spring mvc框架:
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.any()) .paths(PathSelectors.any()) .build(); } }
四、應用啟動與訪問
啟動Spring Boot或spring mvc應用。Swagger將自動生成API文檔。默認情況下,可在瀏覽器訪問http://localhost:8080/swagger-ui.html (端口號根據實際情況調整)查看API文檔。
五、端口訪問問題解決
如果遇到端口訪問問題,可修改啟動命令,例如使用java -jar命令啟動時,添加參數允許外部訪問:
java -jar -Dserver.address=0.0.0.0 your-application.jar
六、Swagger Editor使用(可選)
Swagger Editor允許在線編輯和測試API文檔。您可以自行搭建或使用在線版本。
6.1 自行搭建Swagger Editor (示例,版本可能需要調整):
- 下載并解壓Swagger Editor:
cd /home/user wget https://github.com/swagger-api/swagger-editor/archive/refs/tags/v3.7.0.tar.gz tar -zxvf swagger-editor-3.7.0.tar.gz mv swagger-editor-3.7.0 swagger-editor
- 安裝HttpServer并配置環境變量:
sudo npm install -g http-server export PATH=$PATH:/home/user/swagger-editor/node_modules/http-server/bin
- 運行Swagger Editor:
cd swagger-editor http-server -p 8080
- 訪問http://your-server-ip:8080 使用Swagger Editor。
以上步驟完成Swagger在Linux系統上的部署。 根據實際項目情況,可能需要進行相應調整。