feign异步调用的方案调研

简介

调研常见的feign异步调用的实现方案

总览

序号方案是否可行详细
1Async + CompletableFuturefeign调用的方式不做修改,在feign上面使用async,completable的包装一层,调用方跟包装类交互并
2CompletableFuture原理同上,只不过不使用async注解
3Async修饰feign指定接口,CompetableFuture作为响应类型Aysnc仅限于同一个应用内部的方法调用,不能直接用于远程服务的调用。
4feign定义时,将返回类型使用CompletableFuture包装
5async修饰feign指定接口此时相当于丢到了线程池,是拿不到执行结果的, 如果这样也满足咱们的需求,那为什么不直接使用线程池呢

方案

Async + CompletableFuture 方案
  1. 注册线程池Bean, 这里只提供一个简单demo (Async默认使用SimpleAsyncTaskExecutor并不是真的线程池,它是不会重用线程的,每次调用都会创建一个新的线程,也没有最大线程数设置。并发大的时候会产生严重的性能问题。)
@Configuration
@EnableAsync
public class FeignConfiguration  {
    @Bean("threadPoolTaskAsyncExecutor")
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(50);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("ExampleFeign-");
        executor.initialize();
        return executor;
    }
}
  1. Feign定义 (按照同步的方式编写)
@FeignClient(name = "demo-provider")
public interface FeignAsyncClient {

    @GetMapping(value = "/demo")
    Person demo();
}
  1. 生成包装类
@Service
public class AsyncFeignServiceImpl implements AsyncFeignService {

    @Autowired
    private FeignAsyncClient feignAsyncClient;

    @Override
    @Async("threadPoolTaskAsyncExecutor")
    public CompletableFuture<Person> getPersonByFeign() {
        return CompletableFuture.completedFuture(feignAsyncClient.demo());
    }
}
  1. 调用包装类,返回
    @GetMapping("/demo")
    public Person demo() throws ExecutionException, InterruptedException {
        CompletableFuture<Person> personByFeign = asyncFeignService.getPersonByFeign();

        System.out.println("demo 做一些其他的事情");

        /**
         * thenApply()方法用于对异步计算的结果进行转换,返回一个新的 CompletableFuture 对象,该对象包含转换后的结果。适用于需要对计算结果进行转换或映射的场景。
         * thenAccept() 方法用于消费异步计算的结果,不返回任何结果,但可以执行一些操作。
         * get() 方法用于获取异步计算的结果,会阻塞当前线程,直到计算完成并返回结果。
         * join() 方法与 get() 方法类似,用于获取异步计算的结果,但不会抛出 checked 异常。
         *
         * */
        Person person = personByFeign.get();
//        personByFeign.thenAccept(System.out::println);


        System.out.println("demo person:" + person);
        return person;
    }
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值