spring@cacheable似乎没有缓存任何东西

xqnpmsa8  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(664)

我有一个微服务正在调用另一个微服务,看看这个微服务是否通过Spring启动执行器启动。我希望缓存结果,以避免每次调用我的微服务时都必须执行此检查。所以第一步是缓存执行此检查的方法,然后让此缓存在x秒后过期。到目前为止,第一步还没有奏效。我不希望输入执行检查的方法,但现在每次都输入isaccountconnectorup()。有什么我不知道的吗?

@Service
public class DepositService {

  public void getCredit(String message) {
    isAccountConnectorUp();

    sendRequestToStream(message);
  }

  @Cacheable(value = "result", key = "#root.method.name", unless = "#result == true")
  private static boolean isAccountConnectorUp() {
    final String uri = "http://localhost:9996/health";
    boolean isUp = false;

    RestTemplate restTemplate = new RestTemplate();

    try {
      String result = restTemplate.getForObject(uri, String.class);
      isUp = true;
    } catch (ResourceAccessException exception) {
      throw new DatabaseException(ACCOUNT_CONNECTOR_IS_DOWN);
    }

    return isUp;
  }

}

我已经将@enablecaching添加到我的应用程序类中。

3hvapo4f

3hvapo4f1#

这个代码实际上有三个错误。
尝试将基于代理的aop应用于 private 方法
尝试将基于代理的aop应用于 static 方法
在使用基于代理的aop时执行内部方法调用。
这个 @Cacheable 将通过aop应用。使用spring时,默认情况下使用代理。这意味着只有当方法调用通过代理时才应用aop通知,因为您已经在代理内部,这将无法工作,因为它绕过了代理。
现在,对于一个基于代理的aop解决方案来说,方法必须是非私有的,而不是私有的 static . 因为目前这些都无法代理。
所以基本上你会遇到这三种情况。最后一个是,有点容易绕过的,通过注入一个对你自己的引用并调用这个方法。

@Service
public class DepositService {

  @Autowired
  private DepositService self;

  public void getCredit(String message) {
    self.isAccountConnectorUp();

    sendRequestToStream(message);
  }

  @Cacheable(value = "result", key = "#root.method.name", unless = "#result == true")
  public boolean isAccountConnectorUp() {
    final String uri = "http://localhost:9996/health";
    boolean isUp = false;

    RestTemplate restTemplate = new RestTemplate();

    try {
      String result = restTemplate.getForObject(uri, String.class);
      isUp = true;
    } catch (ResourceAccessException exception) {
      throw new DatabaseException(ACCOUNT_CONNECTOR_IS_DOWN);
    }

    return isUp;
  }

}

如果你真的不想改变可见性和 static 方法的性质。停止使用基于代理的aop,使用编译时编织或加载时编织来修改类的字节码。但是,这会给构建或启动应用程序的方式带来复杂性。
注意:您的缓存没有像以前那样工作 unless 条款。如果值为 true ,将不会缓存异常。因此,即使使用缓存,也无法有效地缓存任何内容。

nhaq1z21

nhaq1z212#

这个 @Cacheable 将生成一个代理,但它只对public方法起作用。另外,正如在注解中提到的,代理将不会在self-call方法上工作。

相关问题