7种方式,教你提升 SpringBoot 项目的吞吐量

这篇具有很好参考价值的文章主要介绍了7种方式,教你提升 SpringBoot 项目的吞吐量。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

  • 一、异步执行

  • 二、增加内嵌Tomcat的最大连接数

  • 三、使用@ComponentScan()定位扫包比@SpringBootApplication扫包更快

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

  • 五、使用 BufferedWriter 进行缓冲

  • 六、Deferred方式实现异步调用

  • 七、异步调用可以使用AsyncHandlerInterceptor进行拦截

hevc?url=https%3A%2F%2Fmmbiz.qpic.cn%2Fmmbiz_jpg%2FsTnayibHfVq6Lzfb0EhVTfCZYcKANvNOFygFVeVSKRmmlsbHl12T4vLKb6RrXlrF3o6kgISlPRxB9yoAAWFaVAg%2F640%3Fwx_fmt%3Djpeg%26tp%3Dwxpic%26wxfrom%3D5%26wx_lazy%3D1%26wx_co%3D1&type=jpg


一、异步执行

实现方式二种:

  1. 使用异步注解@aysnc、启动类:添加@EnableAsync注解

  2. JDK 8本身有一个非常好用的Future类——CompletableFuture

@AllArgsConstructor
public 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);
    }
  
}

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/ruoyi-vue-pro

  • 视频教程:https://doc.iocoder.cn/video/

二、增加内嵌Tomcat的最大连接数

@Configuration
public 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);
        }
    }

}

基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/yudao-cloud

  • 视频教程:https://doc.iocoder.cn/video/

三、使用@ComponentScan()定位扫包比@SpringBootApplication扫包更快

四、默认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>

五、使用 BufferedWriter 进行缓冲

六、Deferred方式实现异步调用

@RestController
public 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进行拦截

@Component
public 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://www.toymoban.com/news/detail-469668.html

到了这里,关于7种方式,教你提升 SpringBoot 项目的吞吐量的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • JavaWEB项目在没有硬件瓶颈的情况下怎么通过简单方法大大增加服务器的吞吐量

    很久之前做了一个springboot的项目,突然发现用户多了之后服务吞吐性能急剧下降,于是想到了一个办法: 通过集群的方法启动多个后端服务,减轻每个服务的压力。 具体做法是在服务器上同时开启10个springboot项目,同一个jar包,用10个脚本打开,每次指定java -jar sb-snapshot-

    2024年02月11日
    浏览(40)
  • Kafka吞吐量

    目录 kafka的架构和流程 小文件对HDFS影响: 解决办法: ⾸先Kafka从架构上说分为⽣产者Broker和消费者,每⼀块都进⾏了单独的优化,⽐如⽣产者快是因为数据的批量发送,Broker快是因为分区,分区解决了并发度的问题,⽽且⽂件是采取的顺序写的形式。顺序写就可以有效的减少磁盘

    2023年04月23日
    浏览(39)
  • qps、tps、吞吐量

      tps全称为Transactions Per Second,指 服务器每秒处理的事务数 。常作为软件测试单位。   解释下这里 事务 的概念:一个事务指客户机向服务器发送请求,服务器做出反应的过程   一个事务的计时方式是从客户机发送请求时开始计时,收到服务器响应后结束计时。用1

    2023年04月10日
    浏览(33)
  • WiFi模块吞吐量测试

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 在WiFi模块选型过程中,工程师会关注到WiFi模块的吞吐量,拿到样品之后,也会进行一个模块吞吐量的测试。本篇就以SKYLAB QCA9531 WiFi模块SKW99的测试角度出发,简单介绍一下WiFi模块怎么测试WiFi吞吐量。

    2024年02月09日
    浏览(34)
  • 了解区块链延迟和吞吐量

    大家鲜少提到如何正确地测量一个(区块链)系统,但它却是系统设计和评估过程中最重要的步骤。 系统中有许多共识协议、各种性能的变量和对可扩展性的权衡。 然而,直到目前都没有一种所有人都认同的可靠方法,能够让人进行苹果对比苹果这种同一范畴内的合理比较

    2024年02月02日
    浏览(35)
  • Rust中的高吞吐量流处理

    本篇文章主要介绍了Rust中流处理的概念、方法和优化。作者不仅介绍了流处理的基本概念以及Rust中常用的流处理库,还使用这些库实现了一个流处理程序。 最后,作者介绍了如何通过测量空闲和阻塞时间来优化流处理程序的性能,并将这些内容同步至Twitter和blog。 此外,作

    2024年02月14日
    浏览(35)
  • TPS、QPS、吞吐量,的计算公式

    TPS (transaction per second)代表每秒执行的事务数量,可基于测试周期内完成的事务数量计算得出。 TPS=事务数/时间(秒) 例如: 用户每分钟执行6个事务,TPS为6 / 60s = 0.10 TPS。 同时我们会知道事务的响应时间(或节拍):60秒完成6个事务,代表每个事务的响应时间或节拍为10秒。

    2024年02月09日
    浏览(41)
  • kafka入门,提高生产者吞吐量练习(七)

    batch.size 批次大小,默认16k linger,ms 等待时间,修改为5-100ms compression.type 压缩snappy RecordAccmulator 缓冲区大小,修改为64m

    2024年02月12日
    浏览(28)
  • 计算机网络(速率、宽带、吞吐量、时延、发送时延)

    单位: bit/s ,或 kbit /s 、 Mbit/s 、 Gbit /s 等。     例如 4 ´ 10 10  bit/s 的数据率就记为 40 Gbit /s。 速率往往是指 额定速率 或 标称速率, 非实际运行速率。         例:人的耳朵能听到的频率最低值为3k,最高值为300k,频宽为300k-3k=297k(k为千赫)         例:如现在的宽

    2024年02月10日
    浏览(32)
  • QPS、TPS、RT、并发用户数、吞吐量

    QPS QPS Queries Per Second 是每秒查询率 ,是 一台服务器 每秒能够相应的查询次数,是对一个特定的查询服务器 在规定时间内 所处理流量多少的衡量标准, 即每秒的响应请求数,也即是最大吞吐能力。 TPS TPS Transactions Per Second 也就是事务数/秒。一个事务是指一个客户机向服务器发

    2024年02月05日
    浏览(38)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包