springboot配合FutureTask/Callable实现并行处理

一、简介

很多同学在学多线程的时候不知道它后来能用在哪儿,这里我提供一个使用多线程的小思路。

现有一个微服务场景,用户想查看某个作者和该作者写的文章。那么他需要从用户服务和文章服务分别去调然后等待结果一起返回。假如用户服务需要2秒返回结果,文章服务需要3秒返回结果,加起来就是5秒,如果业务在复杂一点可能还会调别的服务,例如订单服务、商品服务。。。那么如此我们的调用时间是累加的。系统的等待时间随着业务复杂不断地提高。
换一种方式,如果用户服务与文章服务并行 ,那么水桶原理大家都知道吧,也就是说最后系统的等待时间是其中一个微服务调用时间最长的,在我的例子中也就是3秒。就算后期业务复杂读提高,也只会等待时间最长的那个服务调用,提升性能和系统吞吐量。

JUC为我们提供了 FutureTask/Callable 实现异步调用并获取返回结果。

FutureTask/Callable 都是JUC(java.util.concurrent)包中的类和接口。

深度了解FutureTask请看这篇:
转载:https://baijiahao.baidu.com/s?id=1630613195863161441&wfr=spider&for=pc

Callable和Runnable的区别


public interface Callable<V> {
  V call() throws Exception;
}

interface Runnable {
  public abstract void run();
}

区别:

1.Callable能接受一个泛型,然后在call方法中返回一个这个类型的值。而Runnable的run方法没有返回值
2.Callable的call方法可以抛出异常,而Runnable的run方法不会抛出异常。

再来看看Future接口:

public interface Future<V> {
  boolean cancel(boolean var1);

  boolean isCancelled();

  boolean isDone();

  V get() throws InterruptedException, ExecutionException;

  V get(long var1, TimeUnit var3) throws InterruptedException, ExecutionException, TimeoutException;
}

get方法用于获取执行任务的返回值。
它的重载方法第二个参数用于指定阻塞时间,如果阻塞时间到了就会抛出异常。

通过例子演示:

首先创建一个线程池,因为每次都创建销毁线程势必造成很大的资源浪费。

@Configuration
public class ThreadPoolConfig {
    /**
     * 默认线程池
     *
     * @return Executor
     */
    @Bean
    public ThreadPoolTaskExecutor defaultThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数目
        executor.setCorePoolSize(16);
        //指定最大线程数
        executor.setMaxPoolSize(64);
        //队列中最大的数目
        executor.setQueueCapacity(16);
        //线程名称前缀
        executor.setThreadNamePrefix("defaultThreadPool_");
        //rejection-policy:当pool已经达到max size的时候,如何处理新任务
        //CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
        //对拒绝task的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //线程空闲后的最大存活时间
        executor.setKeepAliveSeconds(60);
        //加载
        executor.initialize();
        return executor;
    }
}

串行方式

 /**
     * 串行接口测试
     * @param authorId
     * @return
     */
    @Override
    public TopicAndAuthor getAuthorAndTopicByAuthorId(String authorId) throws InterruptedException {
        Long timeStart = System.currentTimeMillis();

        Author author = cacheDao.selectAuthorById(Integer.parseInt(authorId));
        sleepThread(2000L);


        List<Topic> topics = cacheDao.selectTopicByAuthor(authorId);
        sleepThread(3000L);

        TopicAndAuthor topicAndAuthor = new TopicAndAuthor(author,topics);
        Long timeEnd = System.currentTimeMillis();
        System.out.println("串行接口耗时"+(timeEnd-timeStart));
        return topicAndAuthor;
    }

在这里插入图片描述
并行方式

 @Override
    public TopicAndAuthor getAuthorAndTopicByAuthorId(String authorId) throws InterruptedException, ExecutionException {
        Long timeStart = System.currentTimeMillis();
        FutureTask<Author> findAuhtorTask = new FutureTask<>(()->{
            System.out.println(Thread.currentThread().getName()+"正在处理...");
            Author author = cacheDao.selectAuthorById(Integer.parseInt(authorId));
            sleepThread(2000L);
            return author;
        });
        FutureTask<List<Topic>> findTopicTask = new FutureTask<>(()->{
            System.out.println(Thread.currentThread().getName()+"正在处理...");
            List<Topic> topics = cacheDao.selectTopicByAuthor(authorId);
            sleepThread(3000L);
            return topics;
        });
        executor.execute(findAuhtorTask);
        executor.execute(findTopicTask);

        TopicAndAuthor topicAndAuthor = new TopicAndAuthor(findAuhtorTask.get(),findTopicTask.get());
        Long timeEnd = System.currentTimeMillis();
        System.out.println("并行接口一共耗时"+(timeEnd-timeStart));
        return topicAndAuthor;
    }

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值