在JAX-RS中处理异步请求中的超时

JAX-RS 2.0在客户端和服务器端都支持异步编程范例。 这篇文章重点介绍了使用JAX-RS(2.0)API在服务器端执行异步REST请求时的超时功能

无需过多介绍,这里是一个快速概述。 为了以异步方式执行方法,您只需

  • 需要指定AsyncResponse接口的实例作为方法参数之一
  • 使用@Suspended批注对其进行批注( 只要 JAX-RS检测到此批注,JAX-RS就会为您注入AsyncResponse的实例)
  • 需要在不同的线程中调用请求–在Java EE 7中推荐的方法是使用托管服务执行程序
@GET
@Produces("text/plain")
public void execute(@Suspended AsyncResponse response){
    System.out.println("Initially invoked on thread - "+ Thread.currentThread.getName() + ". This will free up soon !");
    new Thread(){
        @Override
        public void run(){
            response.resume("executed asynchronously on thread - "+ Thread.currentThread.getName());
        }
    }.start();
}

//JDK 8 version - passing a Runnable (in form of a Lambda Expression) to a thread

@GET
@Produces("text/plain")
public void execute(@Suspended AsyncResponse response){
    System.out.println("Initially invoked on thread - "+ Thread.currentThread.getName() + ". This will free up soon !");
    new Thread(() -> response.resume("executed asynchronously on thread - "+ Thread.currentThread().getName())).start();
}

在幕后?

服务器和客户端之间的基础I / O连接不受影响。 但是在某些情况下,您可能不希望客户端永远等待响应。 在这种情况下,您可以分配超时(阈值)

超时的默认行为是HTTP 503响应。 如果要覆盖此行为,则可以实现TimeoutHandler并将其注册到AsyncResponse。 如果您使用的是Java 8,则无需麻烦使用单独的实现类甚至是匿名内部类-您只需提供Lambda表达式即可,因为TimeoutHandler是具有单个抽象方法功能接口

@GET
@Produces("text/plain")
public void execute(@Suspended AsyncResponse response){
    System.out.println("Initially invoked on thread - "+ Thread.currentThread.getName() + ". This will free up soon !");
    //just having this would result in HTTP 503 after 10 seconds
    response.setTimeout(10, TimeUnit.SECONDS); 
    //client will recieve a HTTP 408 (timeout error) after 10 seconds
    response.setTimeoutHandler((asyncResp) -> asyncResp.resume(Response.status(Response.Status.REQUEST_TIMEOUT)).build());
    new Thread(() -> {
                try {
                    Thread.sleep(11000);
                } catch (InterruptedException ex) {
                   //ignoring
                }
            }).start();
}

干杯!

翻译自: https://www.javacodegeeks.com/2015/03/handling-time-outs-in-async-requests-in-jax-rs.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值