基于Servlet实现请求的隔离的代码实现

1.接受请求

@RequestMapping("/book")
public void getBook(
  HttpServletRequest request;
  @RequestParam(value="skuId") final Long skuId;
  @RequestParam(value="cat1") final Integer cat1;
  @RequestParam(value="cat2") final Integer cat2
) throws Exception
{
  oneLevelAsyncContext.submitFuture(request,()->bookService.getBook(skuId,cat1,cat2));
}

2.业务线程池封装

public void submitFuture{
  
  final HttpServletRequest req,final Callable<Object> task){
    final String uri = req.getRquestURI();
    final Map<String,String[]> params = req.getParameterMap();
    final AsyncContext asyncContext = req.startAsync();
    asyncContext.getRequest().setAttribute("uri",uri);
    asyncContext.getRequest().setAttribute("params",params);
    asyncContext.setTimeout(asyncTimeoutInSeconds*1000);
    if(asyncListener != null){
      asyncContext.addListener(asyncListener);
    }

    executor.submit(new CanceledCallable(asyncContext){
     @Override
     public Object call() throws Exception{
       Object.o = task.call();//业务处理掉用
       if(o == null){
         callback(asyncContext,o,uri,params);
       }
       if(o instanceof CompletableFuture){
         CompletableFuture<Object> future = (CompletableFuture<Object>)o;
         future.thenAccept(resultObject->
         .callback(asyncContext,resultObject,uri,params)
         .exceptionally(e->
         callback(asynccontext,"",uri,params))
         return null;);
       })else if(o instanceof String){
         callback(asyncContext,o,uri,params);
       }
       return null;
    }
    });
  }
}


private void callback(AsyncContext asyncContext,Object result,String uri,Map<String,String[]> params){
  HttpServletResponse resp = (HttpServletResponse) asyncContext.getResponse();
  try{
    if(result instanceof String){
      write(resp,(String)String);
    }else{
      write(resp,JSONUtils.toJSON(result));
    }
  }catch(Throwable e){
    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);//程序内部错误
    try{
      LOG.error("get info error,uri:(), params: {}");
    }catch(Exception ex){}
  }finally{
    asyncContext.complete();
  }
}

3.线程池初始化

public void afterPropertiesSer() throws Exception{
  
  String[] poolSize = poolSize.aplit("_");
  //初始化线程池大小
  int corePoolSize = Integer.valueOf(poolSize[0]);
  //最大线程池大小
  int maximumPoolSize = Integer.valueOf(poolSize[1]);
  queue = new LinkedBlockingDeque<Runnable>(queueCapacity);
  executor = new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTimeinSeconds,TimeUnit.SECONDS,queue);
  executor.allowCoreThreadTimeout(true);
  executor.serRejectedExeturionHandler(
    new RejectedExecutionHandler(){
      @Override
      public void rejectedExecution(Runnable r,ThreadPoolExecutor executor){
        if(r instanceof CanceledCallable){
          CanceledCallable cc = ((CanceledCallable)r)
          AsyncContext asyncContext = cc.asyncContext;
          if(asyncContext != null){
            try{
              ServletRequest req = asyncContext.getRequest();
              String uri = (String)req.getAttribute("uri");
              Map params = (Map)req.getAttribute("params");
              LOG.error("async request rejected,uri:{},params{}",uri,JSONUtils.toJSON(params));
            }catch(Exception e){}
            try{
              HttpServletResponse resp = (HttpServletResponse) asynContext.getResponse();
              resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }finally{
              asyncContext.complete();
            })
          }

        }

      }

    }

  );
  
  if(asyncListener == null){
    asyncListener = new AsyncListener(){
      @Override
      public void onComplete(AsyncEvent event) throws IOException{};
      @Override
      public void onTimeout(AsyncEvent event) throws IOException{
        AsyncContext asyncContext = event.getAsyncContext();
        try{
          ServletRequest req = asyncContext.getRequest();
          String uri = (String) req.getAttribute("uri");
          Map params = (Map)req.getAttribute("params");
          LOG.error("async request timeout,uri:{}",uri,JSONUtils.toJSON(params));
        }catch(){}
        try{
          HttpServletResponse resp = (HttpServletResponse) asyncContext.getResponse();
          resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }finally{
          asyncContext.complete();
        }
      }

      @Override
      public void onError(AsyncEvent event) throws IOException{
       //省略代码error
     }

     @Override
     public void onStartAsync(AsyncEvent event) throws IOException{}
    }

  }

}

4.tomcat 的server.xml配置

<connector port="1601" asyncTimeout="100000"
  acceptCount="10240" maxConnections="10240" acceptorThreadCount="1" minSpareThreads="1"
  maxThreads="1" redirectPort="8443" 
  processorCache="1024" URIEncoding="UTF-8"
  protocol="org.apache.coyote.http11.HttpNioProtocol"
  enableLookups="false"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值