一、异步执行

实现形式二种:

  • 应用异步注解 @aysnc、启动类:增加 @EnableAsync 注解
  • JDK 8 自身有一个十分好用的 Future 类——CompletableFuture
@AllArgsConstructorpublic class AskThread implements Runnable{    private CompletableFuture<Integer> re = null;    public void run() {        int myRe = 0;        try {            myRe = re.get() * re.get();        } catch (Exception e) {            e.printStackTrace();        }        System.out.println(myRe);    }    public static void main(String[] args) throws InterruptedException {        final CompletableFuture<Integer> future = new CompletableFuture<>();        new Thread(new AskThread(future)).start();        //模仿长时间的计算过程        Thread.sleep(1000);        //告知实现后果        future.complete(60);    }}

在该示例中,启动一个线程,此时 AskThread 对象还没有拿到它须要的数据,执行到 myRe = re.get() * re.get() 会阻塞。

咱们用休眠 1 秒来模仿一个长时间的计算过程,并将计算结果通知 future 执行后果,AskThread 线程将会继续执行。

public class Calc {    public static Integer calc(Integer para) {        try {            //模仿一个长时间的执行            Thread.sleep(1000);        } catch (InterruptedException e) {            e.printStackTrace();        }        return para * para;    }    public static void main(String[] args) throws ExecutionException, InterruptedException {        final CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> calc(50))                .thenApply((i) -> Integer.toString(i))                .thenApply((str) -> "\"" + str + "\"")                .thenAccept(System.out::println);        future.get();    }}

CompletableFuture.supplyAsync 办法结构一个 CompletableFuture 实例,在 supplyAsync() 办法中,它会在一个新线程中,执行传入的参数。

在这里它会执行 calc() 办法,这个办法可能是比较慢的,但这并不影响 CompletableFuture 实例的结构速度,supplyAsync() 会立刻返回。

而返回的 CompletableFuture 实例就能够作为这次调用的契约,在未来任何场合,用于取得最终的计算结果。

supplyAsync 用于提供返回值的状况,CompletableFuture 还有一个不须要返回值的异步调用办法 runAsync(Runnable runnable),个别咱们在优化 Controller 时,应用这个办法比拟多。

这两个办法如果在不指定线程池的状况下,都是在 ForkJoinPool.common 线程池中执行,而这个线程池中的所有线程都是 Daemon(守护)线程,所以,当主线程完结时,这些线程无论执行结束都会退出零碎。

外围代码:

CompletableFuture.runAsync(() ->   this.afterBetProcessor(betRequest,betDetailResult,appUser,id));

异步调用应用 Callable 来实现:

@RestController  public class HelloController {    private static final Logger logger = LoggerFactory.getLogger(HelloController.class);    @Autowired      private HelloService hello;    @GetMapping("/helloworld")    public String helloWorldController() {        return hello.sayHello();    }    /**     * 异步调用restful     * 当controller返回值是Callable的时候,springmvc就会启动一个线程将Callable交给TaskExecutor去解决     * 而后DispatcherServlet还有所有的spring拦截器都退出主线程,而后把response放弃关上的状态     * 当Callable执行完结之后,springmvc就会重新启动调配一个request申请,而后DispatcherServlet就从新     * 调用和解决Callable异步执行的返回后果, 而后返回视图     *     * @return     */      @GetMapping("/hello")    public Callable<String> helloController() {        logger.info(Thread.currentThread().getName() + " 进入helloController办法");        Callable<String> callable = new Callable<String>() {            @Override              public String call() throws Exception {                logger.info(Thread.currentThread().getName() + " 进入call办法");                String say = hello.sayHello();                logger.info(Thread.currentThread().getName() + " 从helloService办法返回");                return say;            }        };        logger.info(Thread.currentThread().getName() + " 从helloController办法返回");        return callable;    }}

异步调用的形式 WebAsyncTask:

@RestController  public class HelloController {    private static final Logger logger = LoggerFactory.getLogger(HelloController.class);    @Autowired      private HelloService hello;        /**     * 带超时工夫的异步申请 通过WebAsyncTask自定义客户端超工夫     *     * @return     */      @GetMapping("/world")    public WebAsyncTask<String> worldController() {        logger.info(Thread.currentThread().getName() + " 进入helloController办法");        // 3s钟没返回,则认为超时        WebAsyncTask<String> webAsyncTask = new WebAsyncTask<>(3000, new Callable<String>() {            @Override              public String call() throws Exception {                logger.info(Thread.currentThread().getName() + " 进入call办法");                String say = hello.sayHello();                logger.info(Thread.currentThread().getName() + " 从helloService办法返回");                return say;            }        });        logger.info(Thread.currentThread().getName() + " 从helloController办法返回");        webAsyncTask.onCompletion(new Runnable() {            @Override              public void run() {                logger.info(Thread.currentThread().getName() + " 执行结束");            }        });        webAsyncTask.onTimeout(new Callable<String>() {            @Override              public String call() throws Exception {                logger.info(Thread.currentThread().getName() + " onTimeout");                // 超时的时候,间接抛异样,让外层对立解决超时异样                throw new TimeoutException("调用超时");            }        });        return webAsyncTask;    }    /**     * 异步调用,异样解决,具体的解决流程见MyExceptionHandler类     *     * @return     */      @GetMapping("/exception")    public WebAsyncTask<String> exceptionController() {        logger.info(Thread.currentThread().getName() + " 进入helloController办法");        Callable<String> callable = new Callable<String>() {            @Override              public String call() throws Exception {                logger.info(Thread.currentThread().getName() + " 进入call办法");                throw new TimeoutException("调用超时!");            }        };        logger.info(Thread.currentThread().getName() + " 从helloController办法返回");        return new WebAsyncTask<>(20000, callable);    }}

二、减少内嵌 Tomcat 的最大连接数

代码如下:
@Configurationpublic class TomcatConfig {    @Bean    public ConfigurableServletWebServerFactory webServerFactory() {        TomcatServletWebServerFactory tomcatFactory = new TomcatServletWebServerFactory();        tomcatFactory.addConnectorCustomizers(new MyTomcatConnectorCustomizer());        tomcatFactory.setPort(8005);        tomcatFactory.setContextPath("/api-g");        return tomcatFactory;    }    class MyTomcatConnectorCustomizer implements TomcatConnectorCustomizer {        public void customize(Connector connector) {            Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();            //设置最大连接数            protocol.setMaxConnections(20000);            //设置最大线程数            protocol.setMaxThreads(2000);            protocol.setConnectionTimeout(30000);        }    }}

应用 @ComponentScan()

三、应用 @ComponentScan() 定位扫包

应用 @ComponentScan() 定位扫包比 @SpringBootApplication 扫包更快。

四、默认 Tomcat 容器改为 Undertow

默认 Tomcat 容器改为 Undertow(Jboss 下的服务器,Tomcat 吞吐量 5000,Undertow 吞吐量 8000)

<exclusions>  <exclusion>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-tomcat</artifactId>  </exclusion></exclusions>

改为:

<dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-undertow</artifactId></dependency>

Spring Boot 根底就不介绍了,举荐下这个实战教程:https://github.com/javastacks/spring-boot-best-practice

五、应用 BufferedWriter 进行缓冲

这里不给大家举例,可自行尝试。

六、Deferred 形式实现异步调用

代码如下:
@RestControllerpublic class AsyncDeferredController {    private final Logger logger = LoggerFactory.getLogger(this.getClass());    private final LongTimeTask taskService;    @Autowired    public AsyncDeferredController(LongTimeTask taskService) {        this.taskService = taskService;    }    @GetMapping("/deferred")    public DeferredResult<String> executeSlowTask() {        logger.info(Thread.currentThread().getName() + "进入executeSlowTask办法");        DeferredResult<String> deferredResult = new DeferredResult<>();        // 调用长时间执行工作        taskService.execute(deferredResult);        // 当长时间工作中应用deferred.setResult("world");这个办法时,会从长时间工作中返回,持续controller外面的流程        logger.info(Thread.currentThread().getName() + "从executeSlowTask办法返回");        // 超时的回调办法        deferredResult.onTimeout(new Runnable(){   @Override   public void run() {    logger.info(Thread.currentThread().getName() + " onTimeout");    // 返回超时信息    deferredResult.setErrorResult("time out!");   }  });        // 解决实现的回调办法,无论是超时还是解决胜利,都会进入这个回调办法        deferredResult.onCompletion(new Runnable(){   @Override   public void run() {    logger.info(Thread.currentThread().getName() + " onCompletion");   }  });        return deferredResult;    }}

七、异步调用能够应用 AsyncHandlerInterceptor 进行拦挡

代码如下:
@Componentpublic class MyAsyncHandlerInterceptor implements AsyncHandlerInterceptor { private static final Logger logger = LoggerFactory.getLogger(MyAsyncHandlerInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)   throws Exception {  return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,   ModelAndView modelAndView) throws Exception {// HandlerMethod handlerMethod = (HandlerMethod) handler;  logger.info(Thread.currentThread().getName()+ "服务调用实现,返回后果给客户端"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)   throws Exception {  if(null != ex){   System.out.println("产生异样:"+ex.getMessage());  } } @Override public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)   throws Exception {  // 拦挡之后,从新写回数据,将原来的hello world换成如下字符串  String resp = "my name is chhliu!";  response.setContentLength(resp.length());  response.getOutputStream().write(resp.getBytes());  logger.info(Thread.currentThread().getName() + " 进入afterConcurrentHandlingStarted办法"); }}

参考资料:

  • https://my.oschina.net/u/3768341/blog/3001731
  • https://blog.csdn.net/liuchuanhong1/article/details/78744138
版权申明:本文为CSDN博主「灬点点」的原创文章,遵循CC 4.0 BY-SA版权协定,转载请附上原文出处链接及本申明。原文链接:https://blog.csdn.net/qq_32447301/article/details/88046026

近期热文举荐:

1.1,000+ 道 Java面试题及答案整顿(2022最新版)

2.劲爆!Java 协程要来了。。。

3.Spring Boot 2.x 教程,太全了!

4.别再写满屏的爆爆爆炸类了,试试装璜器模式,这才是优雅的形式!!

5.《Java开发手册(嵩山版)》最新公布,速速下载!

感觉不错,别忘了顺手点赞+转发哦!