美文网首页Spring 开发SpringFrameworkSpring
spring 多线程异步调用 - 提高程序执行效率

spring 多线程异步调用 - 提高程序执行效率

作者: 殷天文 | 来源:发表于2018-09-14 16:02 被阅读23次

demo 来源:https://spring.io/guides/gs/async-method/

为什么要用异步?

当需要调用多个服务时,使用传统的同步调用来执行时,是这样的

  • 调用服务A
  • 等待服务A的响应
  • 调用服务B
  • 等待服务B的响应
  • 调用服务C
  • 等待服务C的响应
  • 根据从服务A、服务B和服务C返回的数据完成业务逻辑,然后结束

如果每个服务需要3秒的响应时间,这样顺序执行下来,可能需要9秒以上才能完成业务逻辑,但是如果我们使用异步调用

  • 调用服务A
  • 调用服务B
  • 调用服务C
  • 然后等待从服务A、B和C的响应
  • 根据从服务A、服务B和服务C返回的数据完成业务逻辑,然后结束

理论上 3秒左右即可完成同样的业务逻辑

Talk is cheap. Show me the code

public class User {

    private String name;
    private String blog;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBlog() {
        return blog;
    }

    public void setBlog(String blog) {
        this.blog = blog;
    }

    @Override
    public String toString() {
        return "User [name=" + name + ", blog=" + blog + "]";
    }

}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.CompletableFuture;

@Service
public class GitHubLookupService {

    private static final Logger logger = LoggerFactory.getLogger(GitHubLookupService.class);

    private final RestTemplate restTemplate;

    public GitHubLookupService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    @Async
    public CompletableFuture<User> findUser(String user) throws InterruptedException {
        logger.info("Looking up " + user);
        String url = String.format("https://api.github.com/users/%s", user);
        User results = restTemplate.getForObject(url, User.class);
        // Artificial delay of 3s for demonstration purposes
        Thread.sleep(3000L);
        return CompletableFuture.completedFuture(results);
    }

}

The findUser method is flagged with Spring’s @Async annotation, indicating it will run on a separate thread. The method’s return type is CompletableFuture<User> instead of User, a requirement for any asynchronous service.

findUser 方法被标记为Spring的 @Async 注解,表示它将在一个单独的线程上运行。该方法的返回类型是 CompleetableFuture<user> 而不是 User,这是任何异步服务的要求。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@SpringBootApplication
@EnableAsync
public class App {

    public static void main(String[] args) {
        // close the application context to shut down the custom ExecutorService
        SpringApplication.run(App.class, args).close();
    }

    @Bean
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("GithubLookup-");
        executor.initialize();
        return executor;
    }

}

The @EnableAsync annotation switches on Spring’s ability to run @Async methods in a background thread pool. This class also customizes the used Executor. In our case, we want to limit the number of concurrent threads to 2 and limit the size of the queue to 500. There are many more things you can tune. By default, a SimpleAsyncTaskExecutor is used.

@EnableAsync 注解开启Spring在后台线程池中运行 @Async 方法的能力。该类也可以自定义使用的 Executor。在我们的示例中,我们希望将并发线程的数量限制为2,并将队列的大小限制为500。有很多你可以配置的东西。默认情况下,使用SimpleAsyncTaskExecutor。

import java.util.concurrent.CompletableFuture;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.gitee.taven.entity.User;
import com.gitee.taven.service.GitHubLookupService;

@Component
public class AppRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(AppRunner.class);

    private final GitHubLookupService gitHubLookupService;

    public AppRunner(GitHubLookupService gitHubLookupService) {
        this.gitHubLookupService = gitHubLookupService;
    }

    @Override
    public void run(String... args) throws Exception {
       // Start the clock
       long start = System.currentTimeMillis();

       // Kick of multiple, asynchronous lookups
       CompletableFuture<User> page1 = gitHubLookupService.findUser("PivotalSoftware");
       CompletableFuture<User> page2 = gitHubLookupService.findUser("CloudFoundry");
       CompletableFuture<User> page3 = gitHubLookupService.findUser("Spring-Projects");

       // Wait until they are all done
       CompletableFuture.allOf(page1,page2,page3).join();

       // Print results, including elapsed time
       float exc = (float)(System.currentTimeMillis() - start)/1000;
       logger.info("Elapsed time: " + exc + " seconds");
       logger.info("--> " + page1.get());
       logger.info("--> " + page2.get());
       logger.info("--> " + page3.get());
    }
    
}

通过实现 CommandLineRunner 调用 service 服务,我们设置了 Thread.sleep(3000L);

运行demo,4.73s 结束战斗!

相关文章

  • spring 多线程异步调用 - 提高程序执行效率

    demo 来源:https://spring.io/guides/gs/async-method/ 为什么要用异步...

  • spring boot 异步实现@Async

    一、异步与同步 异步调用:程序在顺序执行时,不等待异步调用的语句返回结果就执行后面的程序; 同步调用:程序按照定义...

  • spring boot中多线程使用实例

    作用:硬件性能固定的情况下,提高程序运行效率,避免程序阻塞 逻辑是,在未用多线程:调用A——等待响应——调用B——...

  • 问题:什么是多线程

    多线程 1个进程中可以开启多条线程,每条线程可以并行(同时)执行不同的任务多线程技术可以提高程序的执行效率 多线程...

  • 线程与进程

    进程 线程 线程的串行 多线程 多线程的原理 多线程的优缺点 - 多线程的优点 - 能适当提高程序的执行效率- 能...

  • 多线程与并发(一):线程的基本概念和用法

    本篇知识点 线程创建 线程重要api 线程状态 应用方面异步调用:主线程执行期间,其他线程异步执行耗时操作提高效率...

  • 07-Java基础-多线程 & 单例

    多线程、单例 线程线程是程序执行的一条路径, 一个进程中可以包含多条线程。多线程并发执行可以提高程序的效率, 可以...

  • SpringBoot 异步调用

    Spring Boot 中的异步调用 通常我们开发的程序都是同步调用的,即程序按照代码的顺序一行一行的逐步往下执行...

  • 012-GCD多线程技术

    多线程 线程是进程内部执行任务的一种途径,多线程技术能适当提高程序执行效率和资源利用率,iOS 中的多线程技术主要...

  • java学习笔记10

    多线程的引入 1.什么是线程线程是程序执行的一条路径, 一个进程中可以包含多条线程多线程并发执行可以提高程序的效率...

网友评论

    本文标题:spring 多线程异步调用 - 提高程序执行效率

    本文链接:https://www.haomeiwen.com/subject/skpogftx.html