版本记录
日期 | 人员 | 类型 | 版本 | 说明 |
---|---|---|---|---|
2019-10-29 | dcmini | 创建 | v1.0.0 |
Swagger codegen
swagger codegen github地址:https://github.com/swagger-api/swagger-codegen
也就是使用swagger的api-docs文件来生成对应服务的 api-client 简化调用方的开发难度。
下面介绍一种 以 Resttemplate 作为调用工具类的生成 api-client 的方法
示例代码
示例代码文件放在github中了 https://github.com/cheninitial/files/raw/master/hello.zip
项目分成两个部分
- hello-client:生成的api-client
- hello-service:服务器端代码
hello-service 中需要添加 swagger 的依赖以及注解,然后我们启动 hello-service 并访问
http://localhost:8082/hello/v2/api-docs 我们会达到如下的一串json字符串。
{
"swagger": "2.0",
"info": {
"title": "swagger codegen 演示"
},
"host": "localhost:8082",
"basePath": "/hello",
"tags": [
{
"name": "HelloController",
"description": "Hello测试接口"
}
],
"schemes": [
"http"
],
"paths": {
"/hello": {
"get": {
"tags": [
"HelloController"
],
"summary": "对某人说 hello",
"operationId": "helloUsingGET",
"consumes": [
"application/json"
],
"produces": [
"*/*"
],
"parameters": [
{
"name": "name",
"in": "query",
"description": "name",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "string"
}
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Forbidden"
},
"404": {
"description": "Not Found"
}
}
}
}
}
}
然后将这串内容放到 hello/hello-client/apiJson/api-docs.json 文件夹下
然后运行swagger-codegen:generate 命令
可以看到已经生成了代码和解释文档
保持 hello-service 处于运行的状态,运行一下 hello-client 测试用例可以看到调用结果了
生成项目中的 READ.me 已经把使用方法写的非常详细了,这里就不再赘述了。
Api client 项目的 pom 文件参数说明
<build>
<plugins>
<plugin>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<inputSpec>${client-docs-path}</inputSpec>
<language>java</language>
<output>${project.basedir}</output>
<apiPackage>${client-base-package-path}.client</apiPackage>
<modelPackage>${client-base-package-path}.model</modelPackage>
<configOptions>
<sourceFolder>src/main/java</sourceFolder>
<dateLibrary>legacy</dateLibrary>
<library>resttemplate</library>
</configOptions>
</configuration>
<executions>
<execution>
<phase>none</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
inputSpec
:也就是api-docs
的路径, 可以是一个 文件目录,也可以是一个URLlanguage
:需要生成的语言,目前只用过java
的,其实还有很多,js
、go
啥的都有output
:生成羡慕的出书路径apiPackage
:api
接口的类的包名modelPackage
: 模型类的包名configOptions
:附加的配置项, 这个项目里的内容是用来配置生成规则的,可以使用
-java -jar swagger-codegen-cli-2.3.1.jar config-help -l java
来查看sourceFolder
: 源码目录dataLibaray
: 使用何种时间处理对象来处理时间属性。library
: 使用何种框架来生成。resttemplate
: 也就是RestTemplate + Jackson
存在的问题
在此记录一下存在的问题,如果大家有解决办法的话可以告诉我
获取 api-docs 和 生成api-client无法在一个步骤中完成
目前我生成api-client 的流程是
- 运行 service 项目
- 访问 */v2/api-docs 获取swagger配置文档
- 拷贝配置文档到 client 项目中
- 然后线下 运行 swagger-codegen 插件生成代码
- 推送到 gitLab 中
- 通过 ci/cd 打包部署到 nexus 中
目前我还没有找到一个办法能够让 1、2、3、4步骤都在 ci/cd 中完成,如果大家有办法的话可以告诉我。