当前位置: 首页 > news >正文

openapi-generator-maven-plugin自动生成HTTP远程调用客户端

Java开发中调用http接口的时候,有很多可选的技术方案,比如:HttpURLConnection、RestTemplate、WebClient、Feign、Retrofit、Okhttp等,今天我们来看一个更优的技术方案OpenAPI Generator(http://openapi-generator.tech/)

OpenAPI Generator

OpenAPI Generator 是一个开源工具集,用于根据 OpenAPI/Swagger 规范文件自动生成客户端 SDK、服务器端存根 (stub) 和 API 文档。支持 50+ 种语言和框架(Java、Python、Go、TypeScript、C#等),支持 OpenAPI 2.0 (Swagger) 和 3.x 规范,可处理 JSON 或 YAML 格式的 API 描述文件。

下面我们来看一下使用openapi-generator-maven-plugin生成利用resttemplate做远程调用的demo。

服务提供者UserService

1)api接口

 @GetMapping("/{id}")public UserDto getById(@PathVariable int id){return db.get(id);}

2)生成openapi-doc的json文件
添加依赖

<dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-starter-webmvc-ui</artifactId><version>2.5.0</version>
</dependency>

访问:http://localhost:8081/v3/api-docs,得到

{"openapi": "3.0.1","info": {"title": "OpenAPI definition","version": "v0"},"servers": [{"url": "http://localhost:8081","description": "Generated server url"}],"paths": {"/{id}": {"get": {"tags": ["user-controller"],"operationId": "getById","parameters": [{"name": "id","in": "path","required": true,"schema": {"type": "integer","format": "int32"}}],"responses": {"200": {"description": "OK","content": {"*/*": {"schema": {"$ref": "#/components/schemas/UserDto"}}}}}}}},"components": {"schemas": {"UserDto": {"type": "object","properties": {"id": {"type": "integer","format": "int32"},"name": {"type": "string"}}}}}
}

服务消费者OrderService

1)引入前面生成的json文件,存放在order服务的src/resources/api/user-api.json。

2)添加openapi-generator-maven-plugin

<!--https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator-maven-plugin-->
<plugin><groupId>org.openapitools</groupId><artifactId>openapi-generator-maven-plugin</artifactId><version>7.12.0</version><executions><execution><id>rest template</id><goals><goal>generate</goal></goals><configuration><inputSpec>${project.basedir}/src/main/resources/api/user-api.json</inputSpec><generatorName>java</generatorName><configOptions><sourceFolder>src/main/java</sourceFolder><java8>true</java8><dateLibrary>java8</dateLibrary><useJakartaEe>true</useJakartaEe></configOptions><output>${project.basedir}/target/generated-sources/openapi</output><!--<packageName>com.github.xjs.user</packageName>--><apiPackage>com.github.xjs.user</apiPackage><modelPackage>com.github.xjs.user.model</modelPackage><invokerPackage>com.github.xjs.user.invoker</invokerPackage><library>resttemplate</library><generateModelTests>false</generateModelTests><generateApiTests>false</generateApiTests><generateApiDocumentation>false</generateApiDocumentation></configuration></execution>
<!--                    add other clients-->
<!--					<execution> -->
<!--					</execution>--></executions>
</plugin>

解释下几个重点的配置项:

  • inputSpec:指定 OpenAPI 规范文件路径:src/main/resources/api/user-api.json,支持 JSON/YAML 格式,可以是本地文件或 URL。
  • generatorName:生成目标为 Java 客户端代码(其他选项如 spring、kotlin 等)。
  • library:resttemplate,使用 Spring 的 RestTemplate 作为 HTTP 客户端库(替代方案:webclient、feign 等)。
  • output: 生成代码的输出目录:target/generated-sources/openapi, 默认会被 Maven 自动添加到编译路径。
  • packageName: com.github.xjs.user, 所有生成代码的根包名(API 类、模型类等会放在此包下)。
  • sourceFolder: src/main/java, 生成的 Java 代码直接输出到 src/main/java(覆盖默认的生成路径结构)。
  • java8:true, 启用 Java 8 特性(如 Optional、函数式接口等)。
  • dateLibrary: java8, 使用 java.time 包(Java 8 的日期时间库,替代 java.util.Date)。
  • useJakartaEe: true, 使用 Jakarta EE 注解(如 @jakarta.annotation.Generated),而非旧的 javax.annotation
  • generateModelTests:false,不生成模型类的测试代码(如 UserTest.java)。
  • generateApiTests:false,不生成 API 接口的测试代码(如 UserApiTest.java)。
  • generateApiDocumentation:false, 不生成 API 文档(如 README.md 或 docs/ 目录)。

3)生成源代码
命令行执行mvn clean compile就会生成对应的http调用代码:

target/generated-sources/openapi/└── src/main/java/└── com/└── github/└── xjs/└── user/├── api/       # API 接口(如 UserApi.java)├── model/     # 数据模型(如 User.java)└── ApiClient.java  # 核心客户端配置

4)服务调用

// 创建ApiClient 
ApiClient apiClient = new ApiClient();
// 设置生产者服务的baseurl
apiClient.setBasePath("http://localhost:8081");
// 创建ControllerApi
UserControllerApi userControllerApi = new UserControllerApi(apiClient);
// 利用ControllerApi远程调用api接口
UserDto user = userControllerApi.getById(userId);

完整的源码下载:https://github.com/xjs1919/learning-demo/tree/master/openapi-generator-demo

http://www.lryc.cn/news/573849.html

相关文章:

  • Java面试复习指南:基础、面向对象、Java 8新特性及并发编程
  • ASP.NET Core API文档与测试实战指南
  • 编程江湖-Git
  • 分库分表下的 ID 冲突问题与雪花算法讲解
  • 【数据结构】_二叉树部分特征统计
  • python基础(3)
  • 【论文阅读 | CVPR 2024 |Fusion-Mamba :用于跨模态目标检测】
  • 利用通义大模型构建个性化推荐系统——从数据预处理到实时API部署
  • 算法-动态规划-钢条切割问题
  • 简单工厂模式,工厂模式和注册工厂模式
  • Go 循环依赖的依赖注入解决方案详解
  • Cache Travel-09-从零开始手写redis(17)v1.0.0 全新版本架构优化+拓展性增强
  • AI三步诊断心理:比ChatGPT更懂人心
  • C#Halcon从零开发_Day14_AOI缺陷检测策略1_Bolb分析+特征分析_饼干破损检测
  • JavaScript性能优化实战
  • MySQL索引分类有哪些?
  • RA4M2开发IOT(9)----动态显示MEMS数据
  • 基于python代码的通过爬虫方式实现TK下载视频(2025年6月)
  • 支付宝携手HarmonyOS SDK实况窗,开启便捷停车生活
  • 湖北理元理律师事务所:构建可持续债务优化的双轨解法
  • all()函数和any()函数
  • Linux->进程概念(精讲)
  • JavaEE-Mybatis进阶
  • 图灵完备之路(数电学习三分钟)----门的多路化
  • 创客匠人行业洞察:创始人 IP 的核心能力构建与长期主义实践
  • YSYX学习记录(十一)
  • Python中使用RK45方法求解微分方程的详细指南
  • mysql 加锁算法 详解
  • OC—多界面传值
  • JAVA集合篇--深入理解ConcurrentHashMap图解版