Swagger接口文檔一鍵生成部署靜態(tài)文檔實現(xiàn)方案

前言

此方案引用了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)境準備

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é)構如下




最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末怒见,一起剝皮案震驚了整個濱河市姑宽,隨后出現(xiàn)的幾起案子炮车,更是在濱河造成了極大的恐慌酣溃,老刑警劉巖纪隙,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件绵咱,死亡現(xiàn)場離奇詭異,居然都是意外死亡艾恼,警方通過查閱死者的電腦和手機麸锉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進店門花沉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人泻拦,你說我怎么就攤上這事忽媒』抻辏” “怎么了隘冲?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵展辞,是天一觀的道長。 經(jīng)常有香客問我罗珍,道長覆旱,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任藕坯,我火速辦了婚禮炼彪,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘辐马。我一直安慰自己齐疙,他們只是感情好,可當我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布赌厅。 她就那樣靜靜地躺著特愿,像睡著了一般勾缭。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上毒嫡,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天兜畸,我揣著相機與錄音碘梢,去河邊找鬼。 笑死肛鹏,一個胖子當著我的面吹牛恩沛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播健田,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼妓局,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了局雄?” 一聲冷哼從身側(cè)響起存炮,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤穆桂,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后灼芭,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體般又,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡茴迁,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年堕义,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片昔馋。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡糖耸,死狀恐怖嘉竟,靈堂內(nèi)的尸體忽然破棺而出洋侨,到底是詐尸還是另有隱情,我是刑警寧澤边苹,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布裁僧,位于F島的核電站,受9級特大地震影響茬底,放射性物質(zhì)發(fā)生泄漏阱表。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一涉馁、第九天 我趴在偏房一處隱蔽的房頂上張望爱致。 院中可真熱鬧蒜鸡,春花似錦、人聲如沸逢防。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽溉箕。三九已至悦昵,卻和暖如春但指,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背棋凳。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工剩岳, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人晓铆。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓尤蒿,卻偏偏與公主長得像,于是被迫代替她去往敵國和親腰池。 傳聞我的和親對象是個殘疾皇子示弓,可洞房花燭夜當晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容