281.4. 示例:PetStore


签出 examples 目录中的 camel-example-rest-swagger 项目中的示例。

例如,如果您想要使用 PetStore 提供的 REST API,只需从 Swagger 规格引用规格 URI 和所需的操作 id,或者下载规格并将其存储在 swagger.json (在 CLASSPATH 中),它将被自动使用。我们使用 undertow 组件来执行 Spring Boot 的所有请求和 Camels excelent 支持。

以下是在 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>
Copy to Clipboard Toggle word wrap

首先定义 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;
}
Copy to Clipboard Toggle word wrap
注意

在 Camel for Spring Boot 中支持将自动创建 UndertowComponent Spring bean,您可以使用 application.properties (或 application.yml)配置它,并使用前缀 camel.component.undertow.。我们在这里定义了 petstore 组件,以便在 Camel 上下文中有一个指定组件,我们可用于与 PetStore REST API 交互,如果这是我们唯一可能使用相同的方式(使用 application.properties)进行配置的 rest-swagger 组件。

现在,在我们的应用程序中,我们可以使用 ProducerTemplate 调用 PetStore REST 方法:

@Autowired
ProducerTemplate template;

String getPetJsonById(int petId) {
    return template.requestBodyAndHeaders("petstore:getPetById", null, "petId", petId);
}
Copy to Clipboard Toggle word wrap
返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2025 Red Hat