第 280 章 示例:PetStore
签出 examples 目录中的 camel-example-rest-openapi 项目中的示例。
例如,如果您想要使用 PetStore 提供的 REST API 仅引用 OpenApi 规格中的规格 URI 和所需操作 id,或者下载规格并将其存储为 CLASSPATH 的 openapi.json (在 root 中),它将被自动使用。让我们使用 Undertow 组件来执行对 Spring Boot 的所有请求和 Camel excelent 支持。
以下是 Maven POM 文件中定义的依赖项:
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-undertow-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-rest-openapi-starter</artifactId>
</dependency>
首先定义 Undertow 组件和 RestOpenApiComponent :
@Bean
public Component petstore(CamelContext camelContext, UndertowComponent undertow) {
RestOpenApiComponent petstore = new RestOpenApiComponent(camelContext);
petstore.setSpecificationUri("https://petstore3.swagger.io/api/v3/openapi.json");
petstore.setDelegate(undertow);
return petstore;
}
对 Spring Boot 的支持将自动创建 UndertowComponent Spring bean,您可以使用前缀 camel.component.undertow.,使用 application.properties (或 application.yml)进行配置。我们在此处定义 petstore 组件,以便在 Camel 上下文中具有命名组件,我们可以使用它来与 PetStore REST API 交互(如果这是我们使用的唯一 rest-openapi 组件,则可能会以同样的方式配置它(使用 application.properties)。
现在,在应用程序中,我们简单地使用 ProducerTemplate 调用 PetStore REST 方法:
@Autowired
ProducerTemplate template;
String getPetJsonById(int petId) {
return template.requestBodyAndHeaders("petstore:getPetById", null, "petId", petId);
}