Spring Cloud 学习笔记 ——Spring Cloud Sleath 收集异步任务信息

收集异步任务信息

直接上步骤代码:

  • 在启动类上加上 @EnableAsyn 注解,开启异步调用
@EnableAsync
@SpringBootApplication
public class Sleath2Application {

    public static void main(String[] args) {
        SpringApplication.run(Sleath2Application.class, args);
    }
    @Bean
    RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
  • 创建一个 HelloService 类,定义异步方法,使用 HelloController 中的接口调用该异步方法
@Service
public class HelloService {
    private static final Logger logger = LoggerFactory.getLogger(HelloService.class);
    @Async
    public String backgroundFun(){
        logger.info("background");
        return backgroundFun2();
    }
    @Async
    public String backgroundFun2(){
        logger.info("background2");
        return backgroundFun3();
    }
    @Async
    public String backgroundFun3() {
        logger.info("background3");
        return "backgroundFun3";
    }
}

在 HelloController 中定义:

    @Autowired
    HelloService helloService;
    @GetMapping("/hello5")
    public String hello5(){
        logger.info("hello5");
        return helloService.backgroundFun();
    }

我是定义了三个异步方法,由第一个开始一次调用,访问 /hello5 ,查看控制台打印结果:
在这里插入图片描述
在这里插入图片描述
可以看到 Spring Cloud Sleath 也能跟踪异步请求,每个异步请求,并没有生成新的 spanId,而是同一个,另外因为是异步,所以浏览器并没有收到 background3 内容。这就是 Spring Cloud Sleath 收集、跟踪异步请求的功能

  • 定时任务
    除了能跟踪异步信息之外,还能跟踪定时任务
  • 在启动类加上 @EnableScheduling,开启定时任务功能
@EnableAsync
@SpringBootApplication
@EnableScheduling
public class Sleath2Application {

    public static void main(String[] args) {
        SpringApplication.run(Sleath2Application.class, args);
    }

    @Bean
    RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
  • 在 HelloService 中定义定时任务,去调用 background 方法
@Scheduled(cron = "0/10 * * * * ?")
    public void schedul(){
        backgroundFun();
    }
  • 重新启动项目,查看控制台
    在这里插入图片描述
    可以看到每次执行都会产生新的 trace,并且调用过程每个 trace 中 spanId 都是一样的。
    在页面调用异步会产生新的 spanId,每个定时任务中,调用异步,不会产生新的 spanId。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值