我如何打开和关闭 BlockHound 检查

How I can turn on and off BlockHound check

我有一些带有 WebFlux 的应用程序,我想使用 BlockHound,但我需要通过 application.properties 中的参数或通过 spring 分析或其他东西来打开和关闭它。 我还想覆盖操作,当锁定操作被捕获时,不会抛出错误但会记录警告。首先,我通过 application.properties:

中的参数
@SpringBootApplication
@Slf4j
public class GazPayApplication {

    public static void main(String[] args) {
            ConfigurableApplicationContext context =
                    SpringApplication.run(GazPayApplication.class, args);
            BlockHoundSwitch blockHoundSwitch = (BlockHoundSwitch)context.getBean("BlockHoundSwitchBean");
            if (blockHoundSwitch.isBlockHoundEnabled()) {
                BlockHound.install(builder ->
                        builder.blockingMethodCallback(it ->
                                log.warn("find block operation: {}", it.toString())));
    }
}

还有我的 BlockHoundSwitch:

@Component("BlockHoundSwitchBean")
@Getter
public class BlockHoundSwitch {
    @Value("${blockhound.enabled}")
    private boolean blockHoundEnabled;
}

它对我有用,但在我看来这个解决方案非常困难并且有点不可预测。 接下来我尝试通过分析解决这个任务:

@Profile("blockhound_enabled")
@Slf4j
@Component()
public class BlockHoundSwitch {

    public BlockHoundSwitch() {
        BlockHound.install(builder ->
                builder.blockingMethodCallback(it ->
                        log.warn("find block operation: {}", it.toString())));
    }
}

而且它也有效。那么,我有几个问题:

  1. 哪种方式更好,为什么,也许还有其他解决方案?
  2. 我需要本地化和记录块操作发生的地方。我怎样才能得到 class 名称和方法,它发生在哪里?

我解决了。也许有人会有用。我通过分析和下面的代码做到了这一点:

@Profile("blockhound_on")
@Slf4j
@Component()
@Getter
public class BlockHoundSwitch {

    public BlockHoundSwitch() {
        BlockHound.install(builder ->
                builder.blockingMethodCallback(it -> {
                    List<StackTraceElement> itemList = Arrays.stream(new Exception(it.toString()).getStackTrace())
                            .filter(i -> i.toString().contains("application.package"))
                            .collect(Collectors.toList());
                    log.warn("find block operation: \n{}", itemList);
                }));
    }
}

其中 application.package - 我在堆栈跟踪中找到的项目的主要包。