当前位置: 移动技术网 > IT编程>开发语言>Java > 详解Spring MVC的异步模式(高性能的关键)

详解Spring MVC的异步模式(高性能的关键)

2019年07月22日  | 移动技术网IT编程  | 我要评论

什么是异步模式

要知道什么是异步模式,就先要知道什么是同步模式,先看最典型的同步模式:

浏览器发起请求,web服务器开一个线程处理,处理完把处理结果返回浏览器。好像没什么好说的了,绝大多数web服务器都如此般处理。现在想想如果处理的过程中需要调用后端的一个业务逻辑服务器,会是怎样呢?

调就调吧,上图所示,请求处理线程会在call了之后等待return,自身处于阻塞状态。这也是绝大多数web服务器的做法,一般来说这样做也够了,为啥?一来“长时间处理服务”调用通常不多,二来请求数其实也不多。要不是这样的话,这种模式会出现什么问题呢?——会出现的问题就是请求处理线程的短缺!因为请求处理线程的总数是有限的,如果类似的请求多了,所有的处理线程处于阻塞的状态,那新的请求也就无法处理了,也就所谓影响了服务器的吞吐能力。要更加好地发挥服务器的全部性能,就要使用异步,这也是标题上所说的“高性能的关键”。接下来我们来看看异步是怎么一回事:

最大的不同在于请求处理线程对后台处理的调用使用了“invoke”的方式,就是说调了之后直接返回,而不等待,这样请求处理线程就“自由”了,它可以接着去处理别的请求,当后端处理完成后,会钩起一个回调处理线程来处理调用的结果,这个回调处理线程跟请求处理线程也许都是线程池中的某个线程,相互间可以完全没有关系,由这个回调处理线程向浏览器返回内容。这就是异步的过程。

带来的改进是显而易见的,请求处理线程不需要阻塞了,它的能力得到了更充分的使用,带来了服务器吞吐能力的提升。

spring mvc的使用——defferedresult

要使用spring mvc的异步功能,你得先确保你用的是servlet 3.0或以上的版本,maven中如此配置:

  <dependency>
   <groupid>javax.servlet</groupid>
   <artifactid>javax.servlet-api</artifactid>
   <version>3.1.0</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupid>org.springframework</groupid>
   <artifactid>spring-webmvc</artifactid>
   <version>4.2.3.release</version>
  </dependency>

我这里使用的servlet版本是3.1.0,spring mvc版本是4.2.3,建议使用最新的版本。

由于spring mvc的良好封装,异步功能使用起来出奇的简单。传统的同步模式的controller是返回modelandview,而异步模式则是返回deferredresult<modelandview>。

看这个例子:

@requestmapping(value="/asynctask", method = requestmethod.get)
public deferredresult<modelandview> asynctask(){
  deferredresult<modelandview> deferredresult = new deferredresult<modelandview>();
  system.out.println("/asynctask 调用!thread id is : " + thread.currentthread().getid());
  longtimeasynccallservice.makeremotecallandunknownwhenfinish(new longtermtaskcallback() {
    @override
    public void callback(object result) {
      system.out.println("异步调用执行完成, thread id is : " + thread.currentthread().getid());
      modelandview mav = new modelandview("remotecalltask");
      mav.addobject("result", result);
      deferredresult.setresult(mav);
    }
  });
}

longtimeasynccallservice是我写的一个模拟长时间异步调用的服务类,调用之,立即返回,当它处理完成时候,就钩起一个线程调用我们提供的回调函数,这跟“图3”描述的一样,它的代码如下:

public interface longtermtaskcallback {
  void callback(object result);
}

public class longtimeasynccallservice {
  private final int corepoolsize = 4;
  private final int needseconds = 3;
  private random random = new random();
  private scheduledexecutorservice scheduler = executors.newscheduledthreadpool(corepoolsize);
  public void makeremotecallandunknownwhenfinish(longtermtaskcallback callback){
    system.out.println("完成此任务需要 : " + needseconds + " 秒");
    scheduler.schedule(new runnable() {
      @override
      public void run() {
        callback.callback("长时间异步调用完成.");
      }
    }, "这是处理结果:)", timeunit.seconds);
  }
}

输出的结果是:

/asynctask 调用!thread id is : 46

完成此任务需要 : 3 秒

异步调用执行完成, thread id is : 47

由此可见返回结果的线程和请求处理线程不是同一线程。

还有个叫webasynctask

返回defferedresult<modelandview>并非唯一做法,还可以返回webasynctask来实现“异步”,但略有不同,不同之处在于返回webasynctask的话是不需要我们主动去调用callback的,看例子:

@requestmapping(value="/longtimetask", method = requestmethod.get)
public webasynctask longtimetask(){
  system.out.println("/longtimetask被调用 thread id is : " + thread.currentthread().getid());
  callable<modelandview> callable = new callable<modelandview>() {
    public modelandview call() throws exception {
      thread.sleep(3000); //假设是一些长时间任务
      modelandview mav = new modelandview("longtimetask");
      mav.addobject("result", "执行成功");
      system.out.println("执行成功 thread id is : " + thread.currentthread().getid());
      return mav;
    }
  };
  return new webasynctask(callable);
}

其核心是一个callable<modelandview>,事实上,直接返回callable<modelandview>都是可以的,但我们这里包装了一层,以便做后面提到的“超时处理”。和前一个方案的差别在于这个callable的call方法并不是我们直接调用的,而是在longtimetask返回后,由spring mvc用一个工作线程来调用,执行,打印出来的结果:

/longtimetask被调用 thread id is : 56

执行成功 thread id is : 57

可见确实由不同线程执行的,但这个webasynctask可不太符合“图3”所描述的技术规格,它仅仅是简单地把请求处理线程的任务转交给另一工作线程而已。

处理超时

如果“长时间处理任务”一直没返回,那我们也不应该让客户端无限等下去啊,总归要弄个“超时”出来。如图:

 

其实“超时处理线程”和“回调处理线程”可能都是线程池中的某个线程,我为了清晰点把它们分开画而已。增加这个超时处理在spring mvc中非常简单,先拿webasynctask那段代码来改一下:

@requestmapping(value="/longtimetask", method = requestmethod.get)
public webasynctask longtimetask(){
  system.out.println("/longtimetask被调用 thread id is : " + thread.currentthread().getid());
  callable<modelandview> callable = new callable<modelandview>() {
    public modelandview call() throws exception {
      thread.sleep(3000); //假设是一些长时间任务
      modelandview mav = new modelandview("longtimetask");
      mav.addobject("result", "执行成功");
      system.out.println("执行成功 thread id is : " + thread.currentthread().getid());
      return mav;
    }
  };
  
  
  webasynctask asynctask = new webasynctask(2000, callable);
  asynctask.ontimeout(
      new callable<modelandview>() {
        public modelandview call() throws exception {
          modelandview mav = new modelandview("longtimetask");
          mav.addobject("result", "执行超时");
          system.out.println("执行超时 thread id is :" + thread.currentthread().getid());
          return mav;
        }
      }
  );
  return new webasynctask(3000, callable);
}

注意看红色字体部分代码,这就是前面提到的为什么callable还要外包一层的缘故,给webasynctask设置一个超时回调,即可实现超时处理,在这个例子中,正常处理需要3秒钟,而超时设置为2秒,所以肯定会出现超时,执行打印log如下:

/longtimetask被调用 thread id is : 59

执行超时 thread id is :61

执行成功 thread id is : 80

嗯?明明超时了,怎么还会“执行成功”呢?超时归超时,超时并不会打断正常执行流程,但注意,出现超时后我们给客户端返回了“超时”的结果,那接下来即便正常处理流程成功,客户端也收不到正常处理成功所产生的结果了,这带来的问题就是:客户端看到了“超时”,实际上操作到底有没有成功,客户端并不知道,但通常这也不是什么大问题,因为用户在浏览器上再刷新一下就好了。:d

好,再来看defferedresult方式的超时处理:

 

  @requestmapping(value = "/asynctask", method = requestmethod.get)
  public deferredresult<modelandview> asynctask() {
    deferredresult<modelandview> deferredresult = new deferredresult<modelandview>(2000l);
    system.out.println("/asynctask 调用!thread id is : " + thread.currentthread().getid());
    longtimeasynccallservice.makeremotecallandunknownwhenfinish(new longtermtaskcallback() {
      @override
      public void callback(object result) {
        system.out.println("异步调用执行完成, thread id is : " + thread.currentthread().getid());
        modelandview mav = new modelandview("remotecalltask");
        mav.addobject("result", result);
        deferredresult.setresult(mav);
      }
    });

    deferredresult.ontimeout(new runnable() {
      @override
      public void run() {
        system.out.println("异步调用执行超时!thread id is : " + thread.currentthread().getid());
        modelandview mav = new modelandview("remotecalltask");
        mav.addobject("result", "异步调用执行超时");
        deferredresult.setresult(mav);
      }
    });

    return deferredresult;
  }

非常类似,对吧,我把超时设置为2秒,而正常处理需要3秒,一定会超时,执行结果如下:

/asynctask 调用!thread id is : 48

完成此任务需要 : 3 秒

异步调用执行超时!thread id is : 51

异步调用执行完成, thread id is : 49

完全在我们预料之中。

异常处理

貌似没什么差别,在controller中的处理和之前同步模式的处理是一样一样的:

  @exceptionhandler(exception.class)
  public modelandview handleallexception(exception ex) {
    modelandview model = new modelandview("error");
    model.addobject("result", ex.getmessage());
    return model;
  }

还要再弄个全局的异常处理啥的,和过去的做法都一样,在此不表了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网