如何使用 .war 格式的 Camel 制作一个可以在 Tomcat 中部署和运行的 Java DSL servlet?



在过去的几天里,我一直在搜索如何在没有任何Tomcat或Camel知识的情况下执行以下操作,我很惊讶我没有找到任何好的资源:

制作一个将部署到Tomcat中的.war文件(例如从Manager App(,该文件将接受给定URI/test上的请求,并将请求转发到PHP中的内部服务,

该服务在localhost:8222/index.php?q=test

上运行。我已经设法有一个工作示例,通过在camel-archetype-java之上构建将请求转发到不同的 url,路由器如下所示:

package camelinaction;
import org.apache.camel.builder.RouteBuilder;
public class MyRouteBuilder extends RouteBuilder {
public void configure() {
String targetUrl = "https://another.service.com/api/test";
from("jetty:http://127.0.0.1:25566/test?matchOnUriPrefix=true")
.to("jetty:" + targetUrl + "?bridgeEndpoint=true&throwExceptionOnFailure=false");
}
}

我还设法从 Camel 中camel-example-servlet-tomcat示例中创建了一个 .war 文件,并在 tomcat 中成功部署了它。该示例在其项目文件夹中没有任何Java代码,基本上仅由.xml文件和一个.html页面组成,当请求由tomcat提供的相关servlet路径时,该页面由Camel servlet提供。 该项目的基本 xml 如下所示:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:camel="http://camel.apache.org/schema/spring"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route id="helloRoute">
<!-- incoming requests from the servlet is routed -->
<from uri="servlet:hello"/>
<choice>
<when>
<!-- is there a header with the key name? -->
<header>name</header>
<!-- yes so return back a message to the user -->
<transform>
<simple>Hi I am ${sysenv.HOSTNAME}. Hello ${header.name} how are you today?</simple>
</transform>
</when>
<otherwise>
<!-- if no name parameter then output a syntax to the user -->
<transform>
<constant>Add a name parameter to uri, eg ?name=foo</constant>
</transform>
</otherwise>
</choice>
</route>
</camelContext>
</beans>

有人将如何结合这两个示例/功能来实现最终目标,即将来自 tomcat 的请求与 Camel 一起转发到不同的端点?

由于您已经将此 WAR 部署在可以处理 HTTP 的 servlet 容器中,因此无需使用 camel-jetty 组件,但可以利用 camel-servlet 和 camel-servlet-listener 组件。

你的第一个例子使用Camel的Java DSL,第二个例子遵循XML DSL,第一次可能有点吓人。 我找不到任何结合特定场景的示例,因此我编写了一个快速演示,该演示可以部署在 servlet 容器中,并且可以将调用路由到另一个 HTTP 服务。这是一个很小的演示,需要一些修改。我用码头测试了它,但还没有尝试把它扔给雄猫。

在 web.xml 文件中,以下部分控制上下文。

<!-- Camel servlet mapping -->
<servlet-mapping>
<servlet-name>CamelServlet</servlet-name>
<url-pattern>/camel/*</url-pattern>
</servlet-mapping>

只有一个 java 文件,即路由配置,如下所示

public class DefaultRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
from("servlet:hello?matchOnUriPrefix=true")
.routeId("HTTP Bridging Route")
.log("Request: ${in.header."+ Exchange.HTTP_METHOD +"} to ${in.header."+ Exchange.HTTP_URI +"}")
.to("https://another.service.com?bridgeEndpoint=true");
}
}

一旦servlet启动,你就可以访问HTTP资源,由Camel支持http://server/<context root>/camel/hello我希望它能帮助你开始。

最新更新