【问题标题】:Accessing the path in inbound-gateway to set a header访问入站网关中的路径以设置标头
【发布时间】:2014-08-06 15:08:50
【问题描述】:

我有几个 http 网关,它们处理不同的 URL 路径,最终使用公共路由器通道将它们路由到服务激活器。在发送到路由器之前,我需要从 http 请求中提取版本和服务名称。版本很简单,我有一个相应的 HTTP 标头。但是,必须从 URL 路径中提取服务名称。

一些例子:

/json/ContactService/query = "ContactService"
/json/ContactService/associations/query ="ContactService"
/json/ContactService/1234 = "ContactService"

我有一个相当蛮力的方法,可以根据 URL 路径确定服务:

String service = null;

URL url = new URL(requestUrl);
String path = url.getPath();

String[] parts = path.split("/");

// iterate over the parts of the url and find the service part
for(String s : parts) {
    if(s.indexOf("Service") > -1) {
        service = s;
    }       
}

但是我不喜欢这种方法,因为好像服务名称会改变,那么我需要更新代码。另外,它没有考虑 URL 的斜线和其他细微差别。理想情况下,我想在网关中使用 SPeL 设置标头,因为每个网关处理不同的路径,我可以使用路径的一部分相应地设置服务名称。

示例(SPeL 的伪代码):

<int-http:inbound-gateway 
        path="/*Service/query, /*Service/count" request-channel="JSONRequestChannel" reply-channel="JSONResponseChannel"
        supported-methods="POST" reply-timeout="5000" request-payload-type="java.lang.String"
        error-channel="CommonErrorChannel" mapped-request-headers="version, HTTP_REQUEST_HEADERS">
        <int-http:header name="service" expression="path.parts[path.parts.length-2]" />
</int-http:inbound-gateway>


<int-http:inbound-gateway 
        path="/*Service/association/query" request-channel="JSONRequestChannel" reply-channel="JSONResponseChannel"
        supported-methods="POST" reply-timeout="5000" request-payload-type="java.lang.String"
        error-channel="CommonErrorChannel" mapped-request-headers="version, HTTP_REQUEST_HEADERS">
        <int-http:header name="service" expression="path.parts[path.parts.length-3]" />
</int-http:inbound-gateway>

我遇到的一个问题是 NPE 试图在 SPeL 中使用 http_requestUrl 标头;当我尝试在 int-header 中使用它时,它似乎没有设置。

【问题讨论】:

    标签: spring-integration spring-ws


    【解决方案1】:

    这是一个先有鸡还是先有蛋的问题 - 创建这些标头时消息还不存在,因此您不能在这些表达式中使用 headers['foo']。实际上,这些标头(URL 等)是在创建消息之前添加的最后一件事;这些表达式没有#this 对象,只有variables listed here#pathVariables 等)。

    为了使其在此处可用,我们必须将其作为变量添加到评估上下文中(类似于#uri)。但这需要改变框架。

    我认为此时您唯一的选择是在网关和路由器之间添加&lt;header-enricher/&gt;(因为这样http_requestUrl 将可用)。

    编辑:

    或者,您可以直接访问HttpServletRequest,使用这个...

    <int-http:header name="foo" 
    expression="T(org.springframework.web.context.request.RequestContextHolder)
    .requestAttributes.request.requestURI"/>
    

    (为便于阅读添加了换行符)

    【讨论】:

    • 添加了另一种选择。
    • 能否请您更新目前导致 404 的“此处列出的变量”网址。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多