我有以下缓存:
public class FaultTolerantCache implements LoadingCache<Object, Object> {
@Getter
private final LoadingCache<Object, Object> cacheImplementation;
public FaultTolerantCache(@NotNull Integer maximumSize,
@NotNull Integer refreshRate,
@NotNull TimeUnit refreshRateTimeUnit,
@NotNull Function<Object, Object> loader,
@NotNull Logger logger) {
this.cacheImplementation = Caffeine.newBuilder()
.maximumSize(maximumSize)
.refreshAfterWrite(refreshRate, refreshRateTimeUnit)
.build(new FaultTolerantCacheLoader(loader, logger));
}
...
我想在我的一项服务中使用它,看起来像
@Service
public class RestServiceImpl implements RestService {
private final RestTemplate restTemplate;
@Getter
private final FaultTolerantCache cache;
public RestServiceImpl(@NotNull @Qualifier(REST_TEMPLATE_BEAN) RestTemplate restTemplate,
@NotNull Properties Properties) {
this.restTemplate = restTemplate;
this.cache = new FaultTolerantCache(
10_000,
properties.getCache().getTtl(),
TimeUnit.MINUTES,
r -> this.fetchType((Long) r, Type.BRAND.toString()),
log);
}
@Override
@CircuitBreaker(name = "def-cb")
public Object getData(Long id, String type) {
return cache.get(id);
}
private Object fetchType(Long id, String type) {...
但是我看到了一个奇怪的事情,我无法传递到队列
r -> this.fetchBrandAndCategory((Long) r, "MYTYPE"),
仅将 (String) r 作为第二个参数,以便有机会动态选择类型,如果我仅将“MYTYPE”作为硬编码字符串传递,它效果很好,但我想让它像 (Long) r 一样打开
你能帮我吗?我应该在代码中重构哪些内容?
看起来您想根据 type 的值动态地将第二个参数传递给 fetchType 方法。但是,您面临的问题是 fetchType 方法需要 String 作为第二个参数,并且您希望传递 (Long) r 作为第二个参数。
一种解决方案可能是修改 fetchType 方法以接受 Object 类型的附加参数并在方法内处理到 String 的转换。这是代码的修改版本:
@Service
公共类 RestServiceImpl 实现 RestService {
private final RestTemplate restTemplate;
@Getter
private final FaultTolerantCache cache;
public RestServiceImpl(@NotNull @Qualifier(REST_TEMPLATE_BEAN) RestTemplate restTemplate,
@NotNull Properties properties) {
this.restTemplate = restTemplate;
this.cache = new FaultTolerantCache(
10_000,
properties.getCache().getTtl(),
TimeUnit.MINUTES,
r -> this.fetchType((Long) r, "MYTYPE"), // Hardcoded "MYTYPE" for now
log);
}
@Override
@CircuitBreaker(name = "def-cb")
public Object getData(Long id, String type) {
return cache.get(id, type);
}
private Object fetchType(Long id, Object type) {
// Convert type to String if necessary
String typeString = type instanceof String ? (String) type : String.valueOf(type);
// Use id and typeString as needed
// ...
return result; // Your actual implementation
}
}
在此修改中,fetchType 现在接受一个 Object 作为第二个参数(类型)。在该方法中,它检查该类型是否已经是 String,如果不是,则将其转换为 String。这样,当在FaultTolerantCache构造函数中调用fetchType时,您可以将(Long) r作为lambda表达式中的第二个参数传递。