如何使用 Spring Boot 和 Apache Camel 创建 RESTful Web 服务?

How to create RESTful Web Service with Spring Boot and Apache Camel?

我正在 Spring 引导项目中学习 Apache Camel,我尝试创建一个 Retful Web 服务,该服务正在启动,但问题是我在调用端点时收到 404。

@Component
@RequiredArgsConstructor
public class RestJavaDsl extends RouteBuilder {

    private final WeatherDataProvider weatherDataProvider;

    @Override
    public void configure() throws Exception {

        from("rest:get:javadsl/weather/{city}?produces=application/json")
                .outputType(WeatherDto.class)
                .process(this::getWeatherData);
    }

    private void getWeatherData(Exchange exchange) {
        String city = exchange.getMessage().getHeader("city", String.class);
        WeatherDto currentWeather = weatherDataProvider.getCurrentWeather(city);

        Message message = new DefaultMessage(exchange.getContext());
        message.setBody(currentWeather);
        exchange.setMessage(message);

    }

}

我创建这个 class 来硬编码一些数据:

@Component
public class WeatherDataProvider {

    private static Map<String, WeatherDto> weatherData = new HashMap<>();

    public WeatherDataProvider() {
        WeatherDto dto = WeatherDto.builder().city("London").temp("10").unit("C").receivedTime(new Date().toString()).id(1).build();
        weatherData.put("LONDON", dto);
    }

    public WeatherDto getCurrentWeather(String city) {
        return weatherData.get(city.toUpperCase());
    }

    public void setCurrentWeather(WeatherDto dto) {
        dto.setReceivedTime(new Date().toString());
        weatherData.put(dto.getCity().toUpperCase(), dto);
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class WeatherDto implements Serializable {
    static int counter = 1;
    private int id = counter++;
    private String city;
    private String temp;
    private String unit;
    private String receivedTime;
}

application.yml

camel:
  component:
    servlet:
      mapping:
        context-path: /services/*

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.dgs</groupId>
    <artifactId>camel-rest-springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>camel-rest-springboot</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
        <camel.version>3.14.0</camel.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.camel.springboot</groupId>
            <artifactId>camel-spring-boot-starter</artifactId>
            <version>${camel.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-test</artifactId>
            <scope>test</scope>
            <version>${camel.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jackson</artifactId>
            <version>${camel.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jaxb</artifactId>
            <version>${camel.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-servlet</artifactId>
            <version>${camel.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.camel.springboot</groupId>
            <artifactId>camel-servlet-starter</artifactId>
            <version>${camel.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.camel.springboot</groupId>
            <artifactId>camel-rest-starter</artifactId>
            <version>${camel.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

服务正在启动,这是控制台日志:

2022-01-24 20:01:40.353  INFO 15796 --- [           main] c.d.c.CamelRestSpringbootApplication     : Starting CamelRestSpringbootApplication using Java 11.0.5 on pc-PC with PID 15796 (D:\Spring Boot\camel-rest-springboot\target\classes started by pc in D:\Spring Boot\camel-rest-springboot)
2022-01-24 20:01:40.357  INFO 15796 --- [           main] c.d.c.CamelRestSpringbootApplication     : No active profile set, falling back to default profiles: default
2022-01-24 20:01:43.583  INFO 15796 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-01-24 20:01:43.604  INFO 15796 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-01-24 20:01:43.604  INFO 15796 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.56]
2022-01-24 20:01:43.820  INFO 15796 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-01-24 20:01:43.821  INFO 15796 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3235 ms
2022-01-24 20:01:45.228  INFO 15796 --- [           main] o.a.c.c.s.CamelHttpTransportServlet      : Initialized CamelHttpTransportServlet[name=CamelServlet, contextPath=]
2022-01-24 20:01:45.233  INFO 15796 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-01-24 20:01:45.592  INFO 15796 --- [           main] o.a.c.impl.engine.AbstractCamelContext   : Message DataType is enabled on CamelContext: camel-1
2022-01-24 20:01:45.607  INFO 15796 --- [           main] o.a.c.impl.engine.AbstractCamelContext   : Routes startup (total:1 started:1)
2022-01-24 20:01:45.607  INFO 15796 --- [           main] o.a.c.impl.engine.AbstractCamelContext   :     Started route1 (rest://get:javadsl/weather/%7Bcity%7D)
2022-01-24 20:01:45.607  INFO 15796 --- [           main] o.a.c.impl.engine.AbstractCamelContext   : Apache Camel 3.14.0 (camel-1) started in 370ms (build:83ms init:269ms start:18ms)
2022-01-24 20:01:45.617  INFO 15796 --- [           main] c.d.c.CamelRestSpringbootApplication     : Started CamelRestSpringbootApplication in 6.569 seconds (JVM running for 8.087)

但是当我尝试调用端点 http://localhost:8080/services/javadsl/weather/london

看起来这个端点不存在,其余的没有创建。我使用了调试器,但未调用方法 getWeatherData()。 而且我认为这个日志不正常:Started route1 (rest://get:javadsl/weather/%7Bcity%7D),它应该是这样的:route1 started and consuming from servlet:/javadsl/weather /%7B城市%7D 教程来自这里:https://www.youtube.com/watch?v=spDjbC8mZf0&t=433s 提前致谢!

您可以从使用官方 camel-archetype-spring-boot maven 原型创建示例项目开始。您可以使用 IDE 或使用以下 maven 命令从 command-line 基于原型生成项目。

mvn archetype:generate -DarchetypeArtifactId="camel-archetype-spring-boot" -DarchetypeGroupId="org.apache.camel.archetypes" -DarchetypeVersion="3.14.0"

现在在 maven 项目文件中 pom.xml 将以下块添加到依赖项中

<dependency>
    <groupId>org.apache.camel.springboot</groupId>
    <artifactId>camel-jetty-starter</artifactId>
</dependency>

请注意,不需要指定版本,因为它由 camel-spring-boot-dependencies BOM(物料清单)在 dependencyManagement 部分提供。

之后,您可以创建新文件 ConfigureCamelContext.java,我们可以在其中配置我们的 CamelContext 并为其提供 RestConfiguration。我们可以通过实现 CamelContextConfiguration@Component 注释来做到这一点。

注释告诉 spring-framework 它应该创建 class 的实例并将其注入到根据其 class-type 或接口请求它的对象。 Camel 配置为自动询问 spring-framework 这些 RestConfiguration 实例,它将继续使用配置 CamelContext。

package com.example;

import org.apache.camel.CamelContext;
import org.apache.camel.spi.RestConfiguration;
import org.apache.camel.spring.boot.CamelContextConfiguration;
import org.springframework.stereotype.Component;

@Component
public class ConfigureCamelContext implements CamelContextConfiguration {

    @Override
    public void beforeApplicationStart(CamelContext camelContext) {
        
        RestConfiguration restConfiguration = new RestConfiguration();
        restConfiguration.setApiComponent("jetty");
        restConfiguration.setApiHost("localhost");
        restConfiguration.setPort(8081);

        camelContext.setRestConfiguration(restConfiguration);
    }

    @Override
    public void afterApplicationStart(CamelContext camelContext) {   
    }
}

这应该适用于 RestDSL and rest-component

将 MySpringBootRouter.java 编辑为如下内容:

package com.example;

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;

@Component
public class MySpringBootRouter extends RouteBuilder {

    static final String CONTET_TYPE_TEXT = "text/plain";

    @Override
    public void configure() {
        
        rest()
            .get("/hello/")
                .route()
                    .setHeader(Exchange.CONTENT_TYPE,  constant(CONTET_TYPE_TEXT))
                    .setBody().constant("Hello world")
                .end()
            .endRest()
            .get("/hello/{name}")
                .route()
                    .setHeader(Exchange.CONTENT_TYPE,  constant(CONTET_TYPE_TEXT))
                    .setBody().simple("Hello ${headers.name}")
                .end()
            .endRest();

        from("rest:get:test?produces=plain/text")
            .setBody().constant("Hello from JavaDSL");
    }
}

注释掉 src/test/java/<grouId>/ 下的 class 因为原型提供的示例测试不适用于 MySpringBootRouter 并且会中断构建。

到运行项目可以使用命令

mvn spring-boot:run

现在您应该可以打开 localhost:8081/hellolocalhost:8081/hello/<Name>localhost:8081/test 以纯文本形式获得响应。