package com yfrog http import ie ucd murmur MurmurHash import net sf e

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.yfrog.http;
import ie.ucd.murmur.MurmurHash;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.Configuration;
import net.sf.ehcache.config.DiskStoreConfiguration;
import net.sf.ehcache.config.CacheConfiguration;
import java.util.Vector;
public class MultiCacheManager {
Vector<CacheManager> cacheManagers = new Vector<CacheManager>();
static final public String DEFAULT_SCHEME = "/disk%d";
public MultiCacheManager(int count) {
for (int i = 0; i< count;++i) {
createCache(i, DEFAULT_SCHEME);
}
}
public MultiCacheManager(int count, String scheme) {
for (int i = 0; i< count;++i) {
createCache(i, scheme);
}
}
private void createCache(int number, String scheme) {
Configuration config = new Configuration();
config.setName("Cache " + String.valueOf(number));
DiskStoreConfiguration diskConfig = new DiskStoreConfiguration();
diskConfig.setPath(String.format(scheme, number));
config.diskStore(diskConfig);
CacheConfiguration cacheConfig = new CacheConfiguration();
cacheConfig.setEternal(false);
cacheConfig.setTimeToIdleSeconds(120);
cacheConfig.setTimeToLiveSeconds(120);
cacheConfig.setDiskSpoolBufferSizeMB(30);
cacheConfig.setDiskExpiryThreadIntervalSeconds(120);
cacheConfig.setMaxBytesLocalHeap("100M");
cacheConfig.setMemoryStoreEvictionPolicy("LRU");
cacheConfig.setName("Cache " + String.valueOf(number));
config.addCache(cacheConfig);
CacheManager cacheManager = CacheManager.newInstance(config);
cacheManagers.add(cacheManager);
}
private CacheManager getCacheManager(String key) {
return cacheManagers.get(getCacheId(key));
}
private Cache getCache(String key) {
CacheManager manager = getCacheManager(key);
return manager.getCache(manager.getCacheNames()[0]);
}
public HttpObject getCachedValue(String key) {
Element value = getCache(key).get(key);
if (value == null) {
return null;
}
return (HttpObject)value.getObjectValue();
}
private int getCacheId(String key) {
final long integerCount = (long)Integer.MAX_VALUE - (long)Integer.MIN_VALUE; // Java int is 32 bit
final long interval = integerCount / cacheManagers.size();
int hash = MurmurHash.hash32(key);
int id = (int)(((long)hash - (long)Integer.MIN_VALUE) / interval);
return id;
}
public void putValue(String key, HttpObject value) {
getCache(key).put(new Element(key, value));
}
}