使用Spring的@Async注释有什么优势?

时间:2019-10-05 05:10:59

标签: java spring spring-boot asynchronous

我正在寻找从Spring Boot Web服务到另一个Web服务的异步调用。我看到了how Spring's @Async annotation can be used,但是我不喜欢它如何编写代码。

下面是一个示例,显示了使用@Async时代码的外观:

@Configuration
@EnableAsync
public class SpringAsyncConfig
{
    @Bean(name = "fruitTaskExecutor")
    public Executor fruitTaskExecutor()
    {
        return new ThreadPoolTaskExecutor();
    }
}

@Component
public class FruitClient
{
    @Async("fruitTaskExecutor")
    public CompletableFuture<List<Fruit>> getFruits(String type)
    {
        CompletableFuture<List<Fruit>> fruitList = [get fruits from another web service];

        return CompletableFuture.supplyAsync(() -> {
            return [get fruits from another web service];
        });
    }
}

@Service
pubilc class FruitComparisonService
{
    @Autowired
    private FruitClient fruitClient;

    public FruitComparison compareApplesAndOranges()
    {
        CompletableFuture<List<Fruit>> appleFuture = fruitClient.getFruits("APPLES");
        CompletableFuture<List<Fruit>> orangeFuture = fruitClient.getFruits("ORANGES");

        List<Fruit> apples = appleFuture.get();
        List<Fruit> oranges = orangeFuture.get();

        return [compare apples and oranges];
    }
}

这里没有使用@Async

@Configuration
public class SpringAsyncConfig
{
    @Bean(name = "fruitTaskExecutor")
    public Executor fruitTaskExecutor()
    {
        return new ThreadPoolTaskExecutor();
    }
}

@Component
public class FruitClient
{
    public List<Fruit> getFruits(String type)
    {
        return [get fruits from another web service];
    }
}

@Service
pubilc class FruitComparisonService
{
    @Autowired
    @Qualifier("fruitTaskExecutor")
    private Executor executor;

    @Autowired
    private FruitClient fruitClient;

    public FruitComparison compareApplesAndOranges()
    {
        CompletableFuture<List<Fruit>> appleFuture =
            CompletableFuture.supplyAsync(() -> fruitClient.getFruits("APPLES"), executor);
        CompletableFuture<List<Fruit>> orangeFuture =
            CompletableFuture.supplyAsync(() -> fruitClient.getFruits("ORANGES"), executor);

        List<Fruit> apples = appleFuture.get();
        List<Fruit> oranges = orangeFuture.get();

        return [compare apples and oranges];
    }
}

使用@Async时,FruitClient类中的public方法必须返回一个Future。我更喜欢事实并非如此。我认为最好由该方法的调用者确定调用是否应该异步。

但是如果我不使用@Async,我会丢失什么吗?看来并没有减少所需的代码行。

注意:出现this question was asked before,但那里给出的答案都不能真正解决问题。

0 个答案:

没有答案