gpt4 book ai didi

c# - 在具有多个键的内存缓存中

转载 作者:太空宇宙 更新时间:2023-11-03 15:56:37 25 4
gpt4 key购买 nike

我需要为我的一个自定义类对象(金融中的安全性)构建一个缓存。类的对象可以通过多种方式识别,因为它有多个标识符,如 PKey、名称、长名称或不同语言的任何其他类型的名称。

因此缓存应该可以根据任何标识符(即多个键)进行搜索。

如何创建这样的缓存?

我正在使用 C# 4.5,但我认为这是一个普遍问题,因此任何方式的解决方案都可以提供帮助

我认为快速有效的解决方案之一是为不同的标识符保留不同的缓存。例如 和具有 类型对象的单个缓存

是否有更新更好的方法来做到这一点?

Edit: When I am accessing the cache all the keys are not known, so I can not make a composite key

最佳答案

也许这段代码会有用:

public class Test12 {
static Map<CacheKey, SecureObject> cache = new ConcurrentHashMap<CacheKey, SecureObject>();

public static void main(String[] args) {
SecureObject secureObject = new SecureObject(new CacheKey("pkey1", "name1", 1L));
cache.put(secureObject.getKey(), secureObject);
secureObject = new SecureObject(new CacheKey("pkey1", "name2", 2L));
if (cache.containsKey(secureObject.getKey())) {
System.out.println("Already in cache.");
}
}
}

class CacheKey {
String pkey;
String name;
Long longName;

CacheKey(String pkey, String name, Long longName) {
this.pkey = pkey;
this.name = name;
this.longName = longName;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;

CacheKey cacheKey = (CacheKey) o;

if (pkey != null && pkey.equals(cacheKey.pkey)) {
return true;
} else {
if (name != null && name.equals(cacheKey.name)) {
return true;
} else {
if (longName != null && longName.equals(cacheKey.longName)) {
return true;
} else {
return false;
}
}
}
}

@Override
public int hashCode() {
int result = 0;

if (pkey != null) {
result = pkey.hashCode();
} else if (name != null) {
result = name.hashCode();
} else if (longName != null) {
result = longName.hashCode();
}

return result;
}
}

class SecureObject {
CacheKey key;

SecureObject(CacheKey key) {
this.key = key;
}

public CacheKey getKey() {
return key;
}

public void setKey(CacheKey key) {
this.key = key;
}
}

打印:

Already in cache.

这不是完整的解决方案。这只是方向。

关于c# - 在具有多个键的内存缓存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23287876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com