Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 最小化依赖服务上缓存命中的设计模式_Java_Caching_Guice - Fatal编程技术网

Java 最小化依赖服务上缓存命中的设计模式

Java 最小化依赖服务上缓存命中的设计模式,java,caching,guice,Java,Caching,Guice,我需要获取依赖于多个服务调用的数据,例如 getInsurancyPrice(id, priceType) { // any call of this method can throw a "NotFoundException" user = getUser(id); car = getCar(user); insurancyCompany = getInsurancyCompany(user, car); price = getPrice(insura

我需要获取依赖于多个服务调用的数据,例如

getInsurancyPrice(id, priceType) {
    // any call of this method can throw a "NotFoundException"

    user = getUser(id);
    car = getCar(user);
    insurancyCompany = getInsurancyCompany(user, car);
    price = getPrice(insurancyCompany, priceType);

    return price;
}
因为这些调用可能代价高昂,而且不太可能更改,所以我想使用缓存(有一些过期时间)

理想情况下,我希望getInsurancyPrice(1,1)去获取第一次调用所需的所有内容,并在所有后续调用中返回与第一次调用相同的内容(即使它是NotFoundException-即负缓存)

还有一个细节:
假设我在调用getInsurancyPrice(1,1)之后调用getInsurancyPrice(1,2)。。。没有理由运行该方法的前3个调用,因为它们不依赖于“priceType”(因此我应该已经缓存了insurancyCompany)。我只希望在这种情况下调用带有预计算值的getPrice()方法
我试图避免让getUser()和getCar()甚至命中缓存,因为我可以从缓存直接跳到getInsurancyCompany()调用

我可以在一个糟糕的设计中使用大量的“如果”来想办法。。但是有没有更好的设计模式可以帮助我呢?

使用。这不包括过期时间,还有更多

对每个调用使用一个缓存实例。使用简单复合对象作为接受多个参数的方法的键,以便可以将它们传递给加载程序


对于第二部分,我将避免担心不必要地命中缓存。这种缓存的全部意义在于,如果命中率比对外部系统的DB调用或HTTP调用快几个数量级,那么它的速度非常快。只需点击缓存。

您真的需要加载整个用户和车辆以获得保险公司吗?如果有足够的用户和车辆ID来获取保险公司和价格,您应该避免使用getUser和getCar电话。嗨,很抱歉没有说清楚。这只是一个试图简化问题的模拟示例。同意,只需创建四个缓存,每个调用一个(只要空间不是问题)。仅确保独立配置缓存,例如不同的过期时间、逐出策略等。谢谢您的回答!我正在尽量减少命中缓存,因为这是一个分布式服务器,缓存不是本地的。它仍然很快(我猜大约5毫秒左右),但最小化似乎是合理的。