博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring Boot - 2.0.6.RELEASE异步任务获取返回值
阅读量:6242 次
发布时间:2019-06-22

本文共 5751 字,大约阅读时间需要 19 分钟。

hot3.png

0.开发环境

  • Spring Boot - 2.0.6.RELEASE
  • JDK - 1.8 or later
  • Spring Framework - 5.0.9 RELEASE
  • Maven - 3.2+
  • IDE - Eclipse or Spring Tool Suite (STS)

1.maven依赖

4.0.0
net.guides.springboot
springboot-async-example
0.0.1-SNAPSHOT
jar
springboot-async-example
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.0.6.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin

2.首先,我们定义一个用户类

package net.guides.springboot.springbootasyncexample.model;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;@JsonIgnoreProperties(ignoreUnknown = true)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 + "]";    }}

3.定义一个查询服务

package net.guides.springboot.springbootasyncexample.service;import java.util.concurrent.CompletableFuture;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 net.guides.springboot.springbootasyncexample.model.User;@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("threadPoolTaskExecutor")    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 1s for demonstration purposes        Thread.sleep(1000 L);        return CompletableFuture.completedFuture(results);    }}

我们看到,其中的findUser方法需要异步执行,并且该方法还有返回值。

4.配置异步线程池

package net.guides.springboot.springbootasyncexample;import java.util.concurrent.CompletableFuture;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;import org.springframework.core.task.TaskExecutor;import org.springframework.scheduling.annotation.EnableAsync;import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import net.guides.springboot.springbootasyncexample.model.User;import net.guides.springboot.springbootasyncexample.service.GitHubLookupService;@SpringBootApplication@EnableAsyncpublic class SpringbootAsyncApplication implements CommandLineRunner {    private static final Logger logger = LoggerFactory.getLogger(SpringbootAsyncApplication.class);    @Autowired    private GitHubLookupService gitHubLookupService;    @Bean("threadPoolTaskExecutor")    public TaskExecutor getAsyncExecutor() {        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();        executor.setCorePoolSize(20);        executor.setMaxPoolSize(1000);        executor.setWaitForTasksToCompleteOnShutdown(true);        executor.setThreadNamePrefix("Async-");        return executor;    }    public static void main(String[] args) {        SpringApplication.run(SpringbootAsyncApplication.class, args);    }    @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");        CompletableFuture < User > page4 = gitHubLookupService.findUser("RameshMF");        // Wait until they are all done        CompletableFuture.allOf(page1, page2, page3, page4).join();        // Print results, including elapsed time        logger.info("Elapsed time: " + (System.currentTimeMillis() - start));        logger.info("--> " + page1.get());        logger.info("--> " + page2.get());        logger.info("--> " + page3.get());        logger.info("--> " + page4.get());    }}

全文来自:[Spring Boot: Creating Asynchronous Methods Using Annotation]()

转载于:https://my.oschina.net/hengbao666/blog/3037183

你可能感兴趣的文章
VS2017 调试期间无法获取到变量值查看
查看>>
Java+SpringBoot实现四则运算
查看>>
【转载】Discriminative Learning和Generative Learning
查看>>
Git中的AutoCRLF与SafeCRLF换行符问题
查看>>
通过Process启动外部程序
查看>>
那些在django开发中遇到的坑
查看>>
cocos2dx lua 绑定之二:手动绑定自定义类中的函数
查看>>
IE CSS HACK
查看>>
北风设计模式课程---深入理解[代理模式]原理与技术
查看>>
php课程 4-14 数组如何定义使用
查看>>
winform托盘时,要运行一个实例,解决办法
查看>>
vagrant up 失败解决办法
查看>>
mysql AM/PM to 24 hours fromat
查看>>
远程唤醒UP Board
查看>>
网页打印
查看>>
Loading——spin.js
查看>>
Hadoop完全分布式环境搭建(四)——基于Ubuntu16.04安装和配置Hadoop大数据环境...
查看>>
Mule ESB工程的部署
查看>>
分离被碰撞物体, 求碰撞冲量
查看>>
js移动端 可移动滑块
查看>>