public static void main(String[] args) {
Cache cache = new Cache("cache1", 2, true, true, 120, 120, false, 120);
CacheManager cacheManager = new CacheManager();
cacheManager.addCache(cache);
String key = "key1";
Element element = new Element(key,"key1");
cache.put(element);
if(cache.get(key)!=null){
System.out.println("存储key为字符串,取值key值为存储key="+cache.get(key).getValue().toString());}
else{
System.out.println("存储key为字符串,取值key值为存储key,取不到缓存信息");
}
String key2 = new String("key2");
Element element2 = new Element(key2, "key2");
cache.put(element2);
if (cache.get(key2) != null) {
System.out.println("存储key为字符串对象,取值key值为存储key=" + cache.get(key2).getValue().toString());
} else {
System.out.println("存储key为字符串对象,取值key值为存储key,取不到缓存信息");
}
if (cache.get("key2") != null) {
System.out.println("存储key为字符串对象,取值key值为字符串=" + cache.get("key2").getValue().toString());
System.out.println("存储key为字符串对象,取值key值为字符串=" + (key2=="key2"));
} else {
System.out.println("存储key为字符串对象,取值key值为字符串,取不到缓存信息");
}
StringBuilder key3 = new StringBuilder("key3");
key3.append(1);
Element element3 = new Element(key3, "key3");
cache.put(element3);
if (cache.get(key3) != null) {
System.out.println("存储key为StringBuilder对象,取值key为存储key=" + cache.get(key3).getValue().toString());
} else {
System.out.println("存储key为StringBuilder对象,取值key为存储key,取不到缓存信息");
}
if (cache.get("key3") != null) {
System.out.println("存储key为StringBuilder对象,取值key为字符串=" + cache.get("key3").getValue().toString());
} else {
System.out.println("存储key为StringBuilder对象,取值key为字符串,取不到缓存信息");
}
StringBuilder key4 = new StringBuilder("key4");
key4.append(1);
Element element4 = new Element(key4.toString(), "key4");
cache.put(element4);
if (cache.get("key41") != null) {
System.out.println("存储key为StringBuilder对象.toString,取值key为字符串=" + cache.get("key41").getValue().toString());
} else {
System.out.println("存储key为StringBuilder对象.toString,取值key为字符串,取不到缓存信息");
}
if (cache.get(key4) != null) {
System.out.println("存储key为StringBuilder对象.toString,取值key为StringBuilder对象=" + cache.get(key4).getValue().toString());
} else {
System.out.println("存储key为StringBuilder对象.toString,取值key为StringBuilder对象,取不到缓存信息");
}
}
运行结果:
存储key为字符串,取值key值为存储key=key1
存储key为字符串对象,取值key值为存储key=key2
存储key为字符串对象,取值key值为字符串=key2
存储key为字符串对象,取值key值为字符串=false
存储key为StringBuilder对象,取值key为存储key=key3
存储key为StringBuilder对象,取值key为字符串,取不到缓存信息
存储key为StringBuilder对象.toString,取值key为字符串=key4
存储key为StringBuilder对象.toString,取值key为StringBuilder对象,取不到缓存信息
总结:ehcache 根据key值获取缓存对象是,传入的参数为Object,Serializable 类型,是通过equals方法来比较key值相同时取缓存数据