caffeine 发生缓存内容被修改以及解决方案-深度克隆
楼主的项目是当redis down机时走caffeine。直接重写了rediscache。后面发现缓存的数据会变化。所以写了点克隆代码。优先使用序列化接口 。然后不行就类型推断。
private Object cloneObject(Object obj) {
if (obj == null) {
return null;
}
// First step: try Apache Commons SerializationUtilsif (obj instanceof Serializable) {try {return SerializationUtils.clone((Serializable) obj);} catch (Exception e) {log.warn("Failed to clone Serializable object using SerializationUtils. Object class: {}",obj.getClass().getName(), e);}}// Second step: try Jackson with type inference and type informationtry {byte[] bytes = objectMapper.writeValueAsBytes(obj);return objectMapper.readValue(bytes, new TypeReference<>() {});} catch (Exception e) {log.warn("Failed to clone object using Jackson with type inference. Object class: {}",obj.getClass().getName(), e);}// If all methods fail, return original objectreturn obj;
}