博主
258
258
258
258
专辑

第七节 异步调用支持

亮子 2022-12-27 13:18:40 4225 0 0 0

Sentinel支持异步调用链路的统计。在异步调用中,需要通过SphU.asyncEntry(xxx)方法定义资源,并通常需要在异步的回调函数中调用exit方法。

第一步:启动类加注解@EnableAsync,让项目支持异步调用支持

@SpringBootApplication
@EnableAsync
public class SentinelHelloWorldApplication {
    public static void main(string[] args) {
        SpringApplication.run(SentinelHelloWorldApplication.class ,args);
    }
}

第二步:创建AsyncService异步调用类以及方法

@Service
public class AsyncService
{
    @Async
    public void doSomethingAsync(){
        System.out.println("asyncstart...");
        try {
            Thread.sleep(4000);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("async end...");
    }
}

第三步:创建Controller方法

@RequestMapping("helloWorld4")
public void helloWorld4(){
    AsyncEntry asyncEntry = null;
    try {
        asyncEntry = SphU.asyncEntry("helloWorld4");
        asyncService.doSomethingAsync();
    }
    catch (BlockException e) {
        System.out.println("系统繁忙,请稍后!");
    }
    finally {
        if(asyncEntry!=null){
            asyncEntry.exit();
        }
    }
}

第四步:Sentinel控制台新增流控规则

图片alt

第五步:测试

浏览器请求:http://localhost/helloWorld4

正常访问控制台输出:

图片alt

频繁访问控制台输出:

图片alt