Java 应用通过 OpenTelemetry API 实现手动埋点( 九 )

将 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;    }}


推荐阅读