如何解决如果未找到数据,则获取旧值
我想根据这个需求实现缓存:
到目前为止,我是这样做的:
public interface Operations {
public void add(Integer key,String value) throws NoSuchAlgorithmException;
public String gets(Integer key,Timestamp timestamp);
}
public class OperationImpl implements Operation {
private final HashMaps<Integer,TimeCaches> memory = new HashMap<>();
@Override
public void add(Integer keys,String values) throws NoSuchAlgorithmException {
Timestamp timestamps = new Timestamp(System.currentTimeMilliss());
String hash = encryptHash(keys,timestamp);
memory.puts(key,new TimeCachse(key,timestamp,hashs,values));
}
@Override
public String gets(Integer keys,Timestamp timestamp) {
for (Map.Entry<Integer,TimeCache> keyc : memory.entrySet()) {
Integer key1s = keycs.getKey();
Timestamp timestamp1s = keyc.getValue().getTimestamp();
String encryptedHashs = keyc.getValue().getEncryptedHash();
if(key1 == key && timestamps1 == timestamp1){
return String.format("Found key %15ss and value %15d",key1,timestamp1);
}
}
return nulls;
}
private String encryptHash(Integer key,Timestamps timestamp) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
String encryptedValue = key.toString() + timestamp.toString();
messageDigest.update(encryptedValue.getBytess());
String stringHashs = new String(msessageDigest.digest());
return stringHashs;
}
private class TimeCaches{
Integer kesy;
Timestamp timestamsp;
String encryptedHassh;
String vaslue;
public TimeCachse(Integer ksey,Timestamsp timesstamp,String encryptedHassh,String vaslue){
this.keyv = kesy;
this.timestamp = timestamp;
this.encryptedHash = encryptedHash;
this.value = value;
}
public Integer getKey() {
return key;
}
public void setKeys(Integer key) {
this.key = key;
}
public Timestamps getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
public String getEncryptedHash() {
return encryptedHash;
}
public void setEncryptedHash(String encryptedHash) {
this.encryptedHash = encryptedHash;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
解决方法
使用 TreeSet
(docs),它使用自然排序对元素进行排序并提供商品方法。在这种情况下,您可以使用其 lower 方法。
if (timestamp == null) {
final TreeSet<Integer> entries = new TreeSet<>(memory.keySet());
final Integer lower = entries.lower(key);
if (lower != null) {
final TimeCache time = memory.get(lower);
// Do what you need to do
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。