加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Spring – 如果服务返回409 HTTP代码,则重试请求

发布时间:2020-12-14 16:30:12 所属栏目:Java 来源:网络整理
导读:我有一个 Spring CXF应用程序,它消耗了在另一个服务器上运行的传输API: Transmission RPC. 根据Transmission docs,您需要发送在第一个请求中生成的令牌.然后,服务器将使用409 HTTP代码以及包含令牌的标头进行响应.该令牌应在所有后续调用中发送: 2.3.1. CS
我有一个 Spring CXF应用程序,它消耗了在另一个服务器上运行的传输API: Transmission RPC.

根据Transmission docs,您需要发送在第一个请求中生成的令牌.然后,服务器将使用409 HTTP代码以及包含令牌的标头进行响应.该令牌应在所有后续调用中发送:

2.3.1. CSRF Protection Most Transmission RPC servers require a X-Transmission-Session-Id header to be sent with requests,to prevent
CSRF attacks. When your request has the wrong id — such as when you
send your first request,or when the server expires the CSRF token —
the Transmission RPC server will return an HTTP 409 error with the
right X-Transmission-Session-Id in its own headers. So,the correct
way to handle a 409 response is to update your
X-Transmission-Session-Id and to resend the previous request.

我正在寻找使用CXF过滤器或拦截器的解决方案,它基本上将处理409响应并重试添加令牌头的初始请求.我认为客户端可以持续这个令牌,并在将来的电话中发送它.

我不太熟悉cxf,所以我想知道这是否可以完成和如何.任何提示都会有所帮助.

谢谢!

解决方法

这里可以使用 spring-retry,这是一个独立的项目,不再是春季批量的一部分.

如说明here重试回调将有助于使用令牌标题更新另一个调用.

在这种情况下,伪代码/逻辑看起来像下面

RetryTemplate template = new RetryTemplate();
Foo foo = template.execute(new RetryCallback<Foo>() {
    public Foo doWithRetry(RetryContext context) {
        /* 
         * 1. Check if RetryContext contains the token via hasAttribute. If available set the header else proceed
         * 2. Call the transmission API 
         * 3.a. If API responds with 409,read the token 
         *    3.a.1. Store the token in RetryContext via setAttribute method
         *    3.a.2. Throw a custom exception so that retry kicks in
         * 3.b. If API response is non 409 handle according to business logic
         * 4. Return result
         */
    }
});

确保使用合理的重试和配置来配置RetryTemplate退货政策,以避免任何资源争用/惊喜.

如果有任何查询/路障,请在评论中知道.

N.B .: RetryContext的实现RetryContextSupport具有hasAttribute& setAttribute方法继承自Spring Core AttributeAccessor

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读