• Spring Boot教程(九)异步方法


    创建工程

    在pom文件引入相关依赖:

    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
            </dependency>
    

      

    创建一个接收数据的实体:

    @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 + "]";
        }
    
    }
    

      

    创建一个请求的 githib的service:

    @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 Future<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(1000L);
            return new AsyncResult<>(results);
        }
    
    }
    

      

    通过,RestTemplate去请求,另外加上类@Async 表明是一个异步任务。

    开启异步任务:

    @SpringBootApplication
    @EnableAsync
    public class Application extends AsyncConfigurerSupport {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
        @Override
        public Executor getAsyncExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setCorePoolSize(2);
            executor.setMaxPoolSize(2);
            executor.setQueueCapacity(500);
            executor.setThreadNamePrefix("GithubLookup-");
            executor.initialize();
            return executor;
        }
    
    }
    

      

    通过@EnableAsync开启异步任务;并且配置AsyncConfigurerSupport,比如最大的线程池为2.

    源码来源

  • 相关阅读:
    10.22(day11) Object类 异常
    10.19(day10)
    10.18(day9)内部类 抽象类 接口
    10.17(day8) Static关键字 包的使用 访问修饰符的权限 设计模式
    paho-mqtt error1: incorrect protocol version解决方法
    Python进阶-pickle/eval/exec
    关联分析算法Apriori和FP-Growth
    LOF聚类分析
    Python进阶-迭代器和生成器
    Linux常见坑
  • 原文地址:https://www.cnblogs.com/allalongx/p/8482046.html
Copyright © 2020-2023  润新知