280.4. 示例: PetStore
在 example 目录中,签出 camel-example-rest-swagger
项目中的 示例
。
例如,如果您使用 PetStore 提供的 REST API 只引用 Swagger 规格中的规范 URI 和所需的操作 ID,或者下载规格并将其作为 swagger.json
(在 root 中)进行自动使用。我们使用 undertow 组件对 Spring Boot 执行所有请求和 Camel 体验支持。
以下是在 Maven POM 文件中定义的依赖关系:
<dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-undertow-starter</artifactId> </dependency> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-rest-swagger-starter</artifactId> </dependency>
首先定义 Undertow 组件和 RestSwaggerComponent :
@Bean public Component petstore(CamelContext camelContext, UndertowComponent undertow) { RestSwaggerComponent petstore = new RestSwaggerComponent(camelContext); petstore.setSpecificationUri("http://petstore.swagger.io/v2/swagger.json"); petstore.setDelegate(undertow); return petstore; }
注意
对 Spring Boot 的 Camel 的支持将自动创建 UndertowComponent
Spring bean,您可以使用带有前缀 camel.component.undertow 的
)进行配置。这里定义了 application.properties
(或 application.
ymlpetstore
组件,以便在 Camel 上下文中有一个指定组件,以便我们可以用来与 PetStore REST API 交互,只要 这是我们
以相同方式配置它(使用 application.properties
)。
现在,在我们的应用程序中,我们只需使用 ProducerTemplate
调用 PetStore REST 方法:
@Autowired ProducerTemplate template; String getPetJsonById(int petId) { return template.requestBodyAndHeaders("petstore:getPetById", null, "petId", petId); }