|
1
|
|
|
package io.mcarle.sciurus.cache; |
|
2
|
|
|
|
|
3
|
|
|
import io.mcarle.sciurus.Sciurus; |
|
4
|
|
|
|
|
5
|
|
|
import java.util.Collections; |
|
6
|
|
|
import java.util.HashMap; |
|
7
|
|
|
import java.util.Map; |
|
8
|
|
|
|
|
9
|
1 |
|
public enum CacheRegister { |
|
10
|
|
|
|
|
11
|
1 |
|
INSTANCE; |
|
12
|
|
|
|
|
13
|
1 |
|
private final CacheSupplier DEFAULT_SUPPLIER = () -> ExpiringMapCache.INSTANCE; |
|
14
|
1 |
|
private final Map<String, CacheSupplier> CACHE_REGISTER = Collections.synchronizedMap(new HashMap<String, CacheSupplier>() { |
|
15
|
|
|
{ |
|
16
|
1 |
|
put(Sciurus.CACHE_GLOBAL, DEFAULT_SUPPLIER); |
|
17
|
1 |
|
put(Sciurus.CACHE_MAP, DEFAULT_SUPPLIER); |
|
18
|
|
|
} |
|
19
|
|
|
}); |
|
20
|
|
|
|
|
21
|
|
|
public void register(String cacheName, CustomCache cache) { |
|
22
|
1 |
|
if (cache == null) throw new IllegalArgumentException("missing cache"); |
|
23
|
1 |
|
register(cacheName, new SimpleCacheSupplier(cache)); |
|
24
|
1 |
|
} |
|
25
|
|
|
|
|
26
|
|
|
public void register(String cacheName, CacheSupplier cacheSupplier) { |
|
27
|
1 |
|
if (cacheSupplier == null) throw new IllegalArgumentException("missing cache supplier"); |
|
28
|
1 |
|
if (cacheName == null || cacheName.isEmpty()) throw new IllegalArgumentException("missing or empty cache name"); |
|
29
|
1 |
|
cacheSupplier.preRegister(); |
|
30
|
1 |
|
CACHE_REGISTER.put(cacheName, cacheSupplier); |
|
31
|
1 |
|
} |
|
32
|
|
|
|
|
33
|
|
|
public boolean deregister(String cacheName) { |
|
34
|
1 |
|
CacheSupplier cacheSupplier = deregisterCache(cacheName); |
|
35
|
1 |
|
if (cacheSupplier != null) { |
|
36
|
1 |
|
cacheSupplier.postDeregister(); |
|
37
|
|
|
} |
|
38
|
1 |
|
return cacheSupplier != null; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
CustomCache getCache(String cacheName) throws CacheException { |
|
42
|
1 |
|
CacheSupplier cacheSupplier = CACHE_REGISTER.get(cacheName); |
|
43
|
1 |
|
if (cacheSupplier == null) throw new CacheException.UnknownCache(); |
|
44
|
|
|
|
|
45
|
|
|
CustomCache cache; |
|
46
|
|
|
try { |
|
47
|
1 |
|
cache = cacheSupplier.get(); |
|
48
|
1 |
|
} catch (Throwable t) { |
|
49
|
1 |
|
throw new CacheException.CacheSupplierThrewException(t); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
1 |
|
if (cache == null) throw new CacheException.CacheSupplierReturnedNull(); |
|
53
|
|
|
|
|
54
|
1 |
|
return cache; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
|
|
58
|
|
|
private CacheSupplier deregisterCache(String cacheName) { |
|
59
|
1 |
|
if (Sciurus.CACHE_GLOBAL.equals(cacheName) || Sciurus.CACHE_MAP.equals(cacheName)) { |
|
60
|
1 |
|
return CACHE_REGISTER.put(cacheName, DEFAULT_SUPPLIER); |
|
61
|
|
|
} else { |
|
62
|
1 |
|
return CACHE_REGISTER.remove(cacheName); |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
} |
|
67
|
|
|
|