如何基于Quarkus OpenAPI Generator生成多系统客户端?
如何用quarkus-openapi-generator生成多个OpenAPI客户端
Maven配置示例
在你的pom.xml里,为每个需要对接的系统添加独立的<execution>块,每个块对应一个客户端的生成逻辑:
<build> <plugins> <plugin> <groupId>io.quarkiverse.openapi.generator</groupId> <artifactId>quarkus-openapi-generator-maven-plugin</artifactId> <version>你的插件版本</version> <executions> <!-- 第一个客户端:对接System A --> <execution> <id>generate-system-a-client</id> <goals> <goal>generate</goal> </goals> <configuration> <!-- 远程OpenAPI文档URL --> <inputSpec>https://example.com/api/system-a/openapi.yaml</inputSpec> <!-- 生成代码的包路径,确保每个客户端唯一 --> <packageName>com.yourcompany.client.systema</packageName> <!-- 客户端唯一标识,用于配置和注入 --> <clientId>system-a</clientId> <generateModels>true</generateModels> <generateApis>true</generateApis> </configuration> </execution> <!-- 第二个客户端:对接System B --> <execution> <id>generate-system-b-client</id> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>https://example.com/api/system-b/openapi.json</inputSpec> <packageName>com.yourcompany.client.systemb</packageName> <clientId>system-b</clientId> <generateModels>true</generateModels> <generateApis>true</generateApis> </configuration> </execution> </executions> </plugin> </plugins> </build>
Gradle配置示例
如果用Gradle,在build.gradle里添加多个生成任务:
plugins { id 'io.quarkus' id 'io.quarkiverse.openapi.generator' version '你的插件版本' } openapiGenerate { // System A客户端 systemAClient { inputSpec = 'https://example.com/api/system-a/openapi.yaml' packageName = 'com.yourcompany.client.systema' clientId = 'system-a' generateModels = true generateApis = true } // System B客户端 systemBClient { inputSpec = 'https://example.com/api/system-b/openapi.json' packageName = 'com.yourcompany.client.systemb' clientId = 'system-b' generateModels = true generateApis = true } }
配置客户端连接信息
在application.properties里为每个客户端配置独立的连接参数:
# System A客户端配置 quarkus.rest-client.system-a.url=https://system-a.example.com/api quarkus.rest-client.system-a.scope=javax.inject.Singleton # System B客户端配置 quarkus.rest-client.system-b.url=https://system-b.example.com/api quarkus.rest-client.system-b.scope=javax.inject.Singleton
在代码中使用不同客户端
生成完成后,每个客户端会在指定的包路径下生成对应的API类和模型。你可以通过@RestClient注解结合clientId来注入对应客户端:
import com.yourcompany.client.systema.api.UsersApi; import com.yourcompany.client.systemb.api.OrdersApi; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; @Path("/demo") public class DemoResource { // 注入System A的客户端 @Inject @RestClient(clientId = "system-a") UsersApi systemAUsersApi; // 注入System B的客户端 @Inject @RestClient(clientId = "system-b") OrdersApi systemBOrdersApi; @GET @Path("/test") public String testClients() { var users = systemAUsersApi.listUsers(); var orders = systemBOrdersApi.listOrders(); return "Fetched " + users.size() + " users and " + orders.size() + " orders"; } }
关键注意事项
- 每个客户端的
clientId必须唯一,否则会出现配置冲突 packageName建议按系统划分,避免生成的类名冲突inputSpec支持远程URL、本地文件路径,甚至classpath下的资源文件
内容的提问来源于stack exchange,提问作者Michael Hampton
相关产品推荐
相关产品推荐

