前言
此方案引用了Swagger2Markup實現(xiàn)將Swagger文檔離線化攀圈。其中采用Java程序調(diào)用Maven命令將Swagger2Markup生成的AsciiDoc代碼轉(zhuǎn)化成HTML文檔峦甩,采用Nginx部署靜態(tài)HTML文檔實現(xiàn)在線訪問,從而達到文檔與源服務隔離部署的目的犬辰。
Swagger2Markup 是 Github 上的開源項目幌缝。Swagger2Markup 可以將 Swagger 生成的文檔轉(zhuǎn)化成流行的格式以便于獨立部署和使用,如:Markdown浴栽、Confluence吃度、AsciiDoc贴硫。
GitHub:https://github.com/Swagger2Markup/swagger2markup
1.環(huán)境準備
- Linux英遭,本文使用CentOS 7
- Nginx亦渗,安裝過程參考:CentOS 7安裝Nginx
- JDK 1.8,安裝過程參考:CentOS 7安裝JDK 1.8
- Maven多律,安裝過程參考:CentOS 7安裝Maven
2.Nginx配置
2.1 創(chuàng)建靜態(tài)資源存儲路徑(需普通賬號可訪問)狼荞,如:/opt/staticfile/swagger
2.2 配置Nginx帮碰,使用戶能正常訪問3.1創(chuàng)建路徑下的資源殉挽。
server {
listen 8081 ;
server_name _;
root /opt/staticfile/swagger;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
3.部署maven代碼
3.1 在普通用戶可訪問的路徑下創(chuàng)建腳本文件斯碌,如:api-doc-pom.xml,添加如下代碼
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.doc.util</groupId>
<artifactId>api-doc</artifactId>
<version>1.0.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<asciidoc.source>./docs</asciidoc.source>
<asciidoc.output>./html</asciidoc.output>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.6</version>
<configuration>
<!-- asciidoc文件目錄 -->
<sourceDirectory>${asciidoc.source}</sourceDirectory>
<!-- 生成HTML的路徑 -->
<outputDirectory>${asciidoc.output}</outputDirectory>
<backend>html</backend>
<sourceHighlighter>coderay</sourceHighlighter>
<attributes>
<!-- 導航欄在左側(cè) -->
<toc>left</toc>
<!-- 顯示菜單層級數(shù) -->
<toclevels>3</toclevels>
<!-- 自動打數(shù)字序號 -->
<sectnums>ture</sectnums>
</attributes>
</configuration>
</plugin>
</plugins>
</build>
</project>
4.編寫接口文檔管理服務
4.1 本文以Swagger接口形式實現(xiàn),大家可以自行補充可視化界面逛裤。
- pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- swagger2markup -->
<dependency>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 引用以下兩個包是防止生成過程中出現(xiàn)找不到類的異常 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-core</artifactId>
<version>1.5.16</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.16</version>
</dependency>
</dependencies>
<repositories>
<repository>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
<id>jcenter-releases</id>
<name>jcenter</name>
<url>http://jcenter.bintray.com</url>
</repository>
</repositories>
- Application.java
@Log4j2
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
log.info("=====開始啟動=====");
SpringApplication.run(Application.class, args);
log.info("=====啟動完成=====");
}
}
- DocControlV1.java
@Log4j2
@Api(tags = "靜態(tài)接口文檔生成器")
@RestController
@RequestMapping(value = "/doc", produces = "application/json;charset=UTF-8")
public class DocControlV1 {
@Autowired
private Config config;
/**
* 生成接口文檔
*
* @param param
* @return
*/
@ApiOperation(value = "生成接口文檔", notes = "生成接口文檔")
@ApiImplicitParam(name = "param", value = "生成接口文檔參數(shù)", required = true, dataType = "GeneratorParam", paramType = "body")
@ApiResponses({ @ApiResponse(code = 10000, message = "操作成功", response = String.class),
@ApiResponse(code = -10001, message = "操作失敗") })
@PostMapping("/generator")
public RespBody<String> generator(@RequestBody GeneratorParam param) {
RespBody<String> responseBody = new RespBody<>();
try {
// 項目名稱
String project = param.getProject();
log.info("project : {}", project);
// 服務地址
String apiDocsUrl = param.getSwaggerUrl().replace("/swagger-ui.html", "/v2/api-docs");
log.info("apiDocsUrl : {}", apiDocsUrl);
// 生成html文檔的代碼存儲路徑
String docsPath = config.getDocPath() + project + "/docs/asciidoc/generated/all";
log.info("docsPath : {}", docsPath);
// 輸出Ascii到單文件
Swagger2MarkupConfig asciiConfig = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.ASCIIDOC).withOutputLanguage(Language.ZH)
.withPathsGroupedBy(GroupBy.TAGS).withGeneratedExamples().withoutInlineSchema().build();
Swagger2MarkupConverter.from(new URL(apiDocsUrl)).withConfig(asciiConfig).build()
.toFile(Paths.get(docsPath));
// 數(shù)據(jù)源存儲地址
String source = config.getDocPath() + project + "/docs";
log.info("source : {}", source);
// 輸出文檔存儲地址
String output = config.getDocPath() + project + "/html";
log.info("output : {}", output);
// 組裝命令
String command = "";
if (config.getOsType().equals("linux")) {
command = "mvn asciidoctor:process-asciidoc -f={0} -Dasciidoc.source={1} -Dasciidoc.output={2}";
} else {
command = "cmd /c mvn asciidoctor:process-asciidoc -f={0} -Dasciidoc.source={1} -Dasciidoc.output={2}";
}
command = command.replace("{0}", config.getPomPath());
command = command.replace("{1}", source);
command = command.replace("{2}", output);
log.info("command : {}", command);
// 執(zhí)行命令
Runtime runtime = Runtime.getRuntime();
Process pro;
pro = runtime.exec(command);
int status = pro.waitFor();
if (status == 0) {
log.info("The command was executed success");
String docUrl = config.getDocUrl() + project + "/html/all.html";
log.info("docUrl : {}", docUrl);
responseBody.setCode(10000);
responseBody.setMsg("操作成功");
responseBody.setValue(docUrl);
} else {
log.info("The command was executed fail");
responseBody.setCode(-10001);
responseBody.setMsg("操作失敗");
}
pro.destroy();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return responseBody;
}
}
- RespBody.java
@Data
public class RespBody<T> {
@ApiModelProperty(value = "響應碼", position = 1)
private Integer code;
@ApiModelProperty(value = "響應信息", position = 2)
private String msg;
@ApiModelProperty(value = "響應內(nèi)容", position = 3)
private T value;
}
- GeneratorParam.java
@Data
public class GeneratorParam implements Serializable {
private static final long serialVersionUID = 5949232055776328416L;
@ApiModelProperty(value = "項目名稱:xxx-app-api阳堕,必填", required = true, position = 1)
private String project;
@ApiModelProperty(value = "Swagger接口文檔地址:http://localhost:8002/swagger-ui.html择克,必填", required = true, position = 2)
private String swaggerUrl;
}
- Config.java
@Data
@Component
public class Config {
// 靜態(tài)接口文檔存儲路徑
@Value("${doc-path:/opt/}")
private String docPath;
// maven代碼存儲路徑
@Value("${pom-path:/opt/pom.xml}")
private String pomPath;
// 系統(tǒng)類型
@Value("${os-type:linux}")
private String osType;
// 接口文檔訪問地址
@Value("${doc-url:http://127.0.0.1:8080/}")
private String docUrl;
}
- Swagger2.java
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("com.doc.control")).paths(PathSelectors.any()).build()
.useDefaultResponseMessages(false); // 關掉默認的http響應碼;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("靜態(tài)接口文檔生成器API文檔").description("靜態(tài)接口文檔生成器API文檔").version("1.0.0").build();
}
}
- application.yml
# 服務端口
server.port: 5000
# 靜態(tài)接口文檔存儲路徑肚邢,注意最后要帶 "/"
doc-path: /opt/staticfile/swagger/
# maven代碼存儲路徑
pom-path: /opt/staticfile/swagger/api-doc-pom.xml
# 接口文檔訪問地址(Nginx)骡湖,注意最后要帶 "/"
doc-url: http://127.0.0.1:8080/
# 操作系統(tǒng):linux、windows
os-type: linux
4.2 服務自行編譯部署到Linux環(huán)境
4.3 服務啟動后谆焊,訪問服務swagger文檔浦夷,如:http://localhost:5000/swagger-ui.html
4.4 調(diào)用接口自動生成并部署靜態(tài)接口文檔劈狐,獲得接口文檔訪問地址懈息,文檔結(jié)構如下