如何使用Sping Boot 和Apache Camel创建REST风格的Web服务?

oxalkeyp  于 2022-11-07  发布在  Apache
关注(0)|答案(1)|浏览(256)

我正在Sping Boot 项目中学习Apache Camel,我尝试创建一个Retful Webservice,该服务正在启动,但问题是当我调用端点时得到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);

    }

}

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

@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)

但是当我尝试调用端点时
看起来这个端点不存在,其余的没有创建。我使用了调试器,但没有调用方法getWeatherData()。我认为这个日志不正常:启动route 1(rest://get:javadsl/weather/%7Bcity%7D),它应该是这样的:route 1从servlet启动并使用:/javadsl/weather/%7Bcity%7D教程来自此处:提前感谢您!

mgdq6dx1

mgdq6dx11#

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

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(物料清单)提供。
之后,您可以创建新文件ConfigureCamelContext.java,在该文件中我们可以配置CamelContext并为其提供RestConfiguration。我们可以通过实现CamelContextConfiguration和@Component注解来实现这一点。
注解告诉spring-framework它应该创建类的示例,并将其注入到基于其类类型或接口请求它的对象中。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) {   
    }
}

这应该适用于RestDSLrest-component
将www.example.com编辑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>/下的类,因为原型提供的示例测试不适用于MySpringBootRouter,并且将中断构建。
要运行项目,可以使用命令

mvn spring-boot:run

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

相关问题