将 Order 转换为 OrderDto 也可以添加一个 span,代码如下所示:
// src/main/java/com/youdianzhishi/orderservice/model/Order.javapackage com.youdianzhishi.orderservice.model;// ......public OrderDto toOrderDto(WebClient webClient, Tracer tracer, Context context) throws Exception { // 创建新的 Span,作为子 Span Span span = tracer.spanBuilder("GET /api/books/batch").setParent(context).startSpan(); try (Scope scope = span.makeCurrent()) { // 切换上下文到子 Span span.setAttribute("order_id", this.getId()); span.setAttribute("status", this.getStatus()); OrderDto orderDto = new OrderDto(); orderDto.setId(this.getId()); orderDto.setStatus(this.getStatus()); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String strDate = formatter.format(this.getOrderDate()); orderDto.setOrderDate(strDate); List<Integer> bookIds = this.getBookIds(); // 假设你有一个可以获取书籍ID的方法 // 将 bookIds 转换为字符串,以便于传递给 WebClient String bookIdsStr = bookIds.stream().map(String::valueOf).collect(Collectors.joining(",")); span.addEvent("get book ids"); span.setAttribute("book_ids", bookIdsStr); // 用 WebClient 调用批量查询书籍的服务接口 // 从环境变量中获取 bookServiceUrl String catalogServiceEnv = System.getenv("CATALOG_SERVICE_URL"); String catalogServiceUrl = catalogServiceEnv != null ? catalogServiceEnv : "http://localhost:8082"; Mono<List<BookDto>> booksMono = webClient.get() // 假设你有一个webClient实例 .uri(catalogServiceUrl + "/api/books/batch?ids=" + bookIdsStr) .retrieve() .bodyToMono(new ParameterizedTypeReference<>() { }); List<BookDto> books = booksMono.block(); span.addEvent("get books info from catalog service"); // 还需要将书籍数量和总价填充到 OrderDto 对象中 int totalAmount = 0; int totalCount = 0; List<BookQuantity> bqs = this.getBookQuantities(); for (BookDto book : books) { // 如果 book.id 在 bqs 中,那么就将对应的数量设置到 book.quantity 中 int quantity = bqs.stream().filter(bq -> bq.getId() == book.getId()).findFirst().get().getQuantity(); book.setQuantity(quantity); totalCount += quantity; totalAmount += book.getPrice() * quantity; } orderDto.setBooks(books); orderDto.setAmount(totalAmount); orderDto.setTotal(totalCount); span.addEvent("calculate total amount and total count"); span.end(); return orderDto; }}
推荐阅读
- 通过诗经楚辞取的公司名字
- 动量定理的应用 动量定理的应用视频讲解
- 深入浅出、玩转Java多线程
- 揭秘十个必知的 JavaScript 3D 库,打造顶级3D炫酷效果!
- 图灵测试已死!ChatGPT通过人类考试也不算,超强AI评估新秀「逻辑谜题」
- 王者荣耀的段位排行榜是通过Redis实现的?
- 我不再写Javascript了
- Java 单元测试及常用语句
- 构建高效的Java网络应用,体验秒级响应
- 谷歌推出 AlloyDB AI,帮助开发者创建生成式 AI 应用