【问题标题】:How to create RESTful Web Service with Spring Boot and Apache Camel?如何使用 Spring Boot 和 Apache Camel 创建 RESTful Web 服务?
【发布时间】:2022-01-24 18:15:41
【问题描述】:

我正在 Spring 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)

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

看起来这个端点不存在,其余的都没有创建。我使用了调试器并且没有调用 getWeatherData() 方法。 而且我认为这个日志不好:Started route1 (rest://get:javadsl/weather/%7Bcity%7D),它应该是这样的: route1 从 servlet:/javadsl/weather/%7Bcity% 启动和消费7D 教程来自这里:https://www.youtube.com/watch?v=spDjbC8mZf0&t=433s 提前谢谢!

【问题讨论】:

    标签: java spring-boot rest apache-camel


    【解决方案1】:

    您可以从使用官方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 实例,它将继续使用 configure 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

    将 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/&lt;grouId&gt;/ 下的类,因为原型提供的示例测试不适用于 MySpringBootRouter 并且会中断构建。

    要运行项目,您可以使用命令

    mvn spring-boot:run
    

    现在您应该可以打开localhost:8081/hellolocalhost:8081/hello/&lt;Name&gt;localhost:8081/test 以获取纯文本回复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-04
      • 2014-09-24
      • 2018-10-25
      • 1970-01-01
      相关资源
      最近更新 更多