为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
Spring

为什么要用异步?

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

  • 调用服务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;@Servicepublic 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@EnableAsyncpublic 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;@Componentpublic 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);

webp

运行demo,4.73s 结束战斗!



作者:殷天文
链接:https://www.jianshu.com/p/d919f4372351


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消