在微服务的开发中,我们经常需要服务之间的调用,并且为了提高效率使用异步的方式进行服务之间的调用,在这种异步的调用情况下会有一个严重的问题,丢失上文下
通过以上图片可以看出异步丢失上下文的原因是不在同一个线程,所有数据不能共享,Wie了解决这个问题,我们就需要把之前线程的请求头上下文,在次存放到其他线程的请求头上下文就行,具体实现如下:
案例:feign异步获取订单明细的案例代码
/*** 获取订单明细的vo* @return*/@Overridepublic OrderConfirmVo orderConfirm() {MemberResponseVo member = OrderInterceptor.threadLocal.get();OrderConfirmVo orderConfirmVo = new OrderConfirmVo();System.out.println("主线程:"+ Thread.currentThread().getId());//获取主线程的请求头信息RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();//考虑到效率问题 使用异步编排CompletableFuture<Void> getAddress = CompletableFuture.runAsync(() -> {//子线程中设置添加主线程的请求头信息 信息共享 否则远程调用异步处理丢失请求头信息RequestContextHolder.setRequestAttributes(requestAttributes);System.out.println("address:"+ Thread.currentThread().getId());//远程获取地址信息List<MemberAddressVo> address = memberFeignService.getAddress(member.getId());orderConfirmVo.setAddress(address);}, executor);CompletableFuture<Void> getItem = CompletableFuture.runAsync(() -> {//子线程中设置添加主线程的请求头信息 信息共享 否则远程调用异步处理丢失请求头信息RequestContextHolder.setRequestAttributes(requestAttributes);System.out.println("item:"+ Thread.currentThread().getId());//远程获取购物项List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();orderConfirmVo.setItems(currentUserCartItems);}, executor).thenRunAsync(()->{List<OrderItemVo> items = orderConfirmVo.getItems();//获取所有商品的idList<String> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());List<Long> skuIds = collect.stream().map(item -> {return Long.parseLong(item);}).collect(Collectors.toList());R<List<SkuHasStockVo>> skusHasStock = wmsFeignService.getSkusHasStock(skuIds);List<SkuHasStockVo> data = skusHasStock.getData(new TypeReference<List<SkuHasStockVo>>() {});if(data!= null){Map<Long, Boolean> collect1 = data.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));orderConfirmVo.setStocks(collect1);}},executor);//异步编排完成之后执行后续操作try {CompletableFuture.allOf(getAddress,getItem).get();} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}orderConfirmVo.setIntegration(member.getIntegration());orderConfirmVo.setPayPrice(orderConfirmVo.getPayPrice());orderConfirmVo.setTotal(orderConfirmVo.getTotal());//TODO 放重处理 生成token令牌储存在redisString token = UUID.randomUUID().toString().replace("-", "");orderConfirmVo.setOrderToken(token);redisTemplate.opsForValue().set(OrderConstant.ORDER_TOKEN+member.getId(),token);return orderConfirmVo;}