栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

@Async 注解实现异步调用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

@Async 注解实现异步调用

这里写自定义目录标题
  • @Async 注解实现异步调用
    • 使用方法
    • 注意事项
    • 示例
      • 创建用户表现层
      • 创建查找服务
      • 应用程序

@Async 注解实现异步调用 使用方法
  1. 在 SpringBootApplication 中添加 @EnableAsync
  2. 使用Bean 方法配置线程池(注意, 用于生产必须配置线程池)
  3. 实现 @Service 类是的spring 上下文能够检测到异步调用服务
  4. 在方法中添加 @Async 注解
  5. 详细请参照示例和注意事项
注意事项
  1. @Async 方法必须在所属的@Service 之外被调用, 不能自己调用@Async方法
  2. 在SpringBootApplication 配置线程池, 推荐使用ThreadPoolTaskExecutor.
  3. 线程池必须限制队列大小, 否则将导致OOM.
  4. setCorePoolSize 和 setMaxPoolSize 建议保持一致
  5. @Async 方法一定要注意实现线程安全, 后面会有文章单独介绍线程池中的线程安全下如何保持高性能
示例 创建用户表现层
package com.example.asyncmethod;

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

}
创建查找服务
package com.example.asyncmethod;

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 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 CompletableFuture.completedFuture(results);
  }

}

GitHubLookupService 类使用 Spring 的 RestTemplate 调用远程 REST (api.github.com/users/),然后转换为用户对象。
类中必须要标有 @Service (或者@Component) 注释,使其成为 Spring 扫描组件的时候,被检测并添加到程序上下文中。
这里是关键, findUser 方法使用 Spring 的 @Async 注解,本例中使用线程池中运行该方法。
方法的返回值要么是void, 要么是Futrue 类, 本例返回类型是 CompletableFuture。

应用程序
package com.example.asyncmethod;

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 AsyncMethodApplication {

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

  @Bean
  public Executor taskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2); //初始并发线程的数量限制
    executor.setMaxPoolSize(2); //最大并发线程的数量限制, 强烈建议初始值和最大值保持一致
    executor.setQueueCapacity(500); //队列大小
    executor.setThreadNamePrefix("example-");
    executor.initialize();
    return executor;
  }

}

必须通过@EnableAsync 注解开启 Spring 在后台线程池中运行 @Async 方法功能。 通过生成bean 来定制 Executor, 本例中为taskExecutor。

  • 异步调用者必须在 @Service 异步调用类之外, 才能生效.
package com.example.asyncmethod;

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

import java.util.concurrent.CompletableFuture;

@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 page1 = gitHubLookupService.findUser("PivotalSoftware");
    CompletableFuture page2 = gitHubLookupService.findUser("CloudFoundry");
    CompletableFuture page3 = gitHubLookupService.findUser("Spring-Projects");

    // Wait until they are all done
    CompletableFuture.allOf(page1,page2,page3).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());

  }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/978914.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号