在Java Web中经常使用缓存,但是如果缓存数据量非常大,则容易出现OOM的情况。
可以使用动态代理,限制缓存容器的容量。
如果达到容量上限,则可以移除过期的缓存数据。
-
import java.lang.reflect.InvocationHandler;
-
import java.lang.reflect.Method;
-
import java.lang.reflect.Proxy;
-
import java.util.HashMap;
-
import java.util.Map;
-
-
public class MapInvocationHandler implements InvocationHandler {
-
-
private Map<String, String> map = new HashMap<String, String>();
-
-
private int limit = 10;
-
-
public MapInvocationHandler(int limit) {
-
this.limit = limit;
-
}
-
-
public MapInvocationHandler() {
-
}
-
-
public Map<String, String> getInstance() {
-
return (Map<String, String>) Proxy.newProxyInstance(map.getClass()
-
.getClassLoader(), map.getClass().getInterfaces(), this);
-
}
-
-
@Override
-
public Object invoke(Object proxy, Method method, Object[] args)
-
throws Throwable {
-
Object result;
-
if ("put".equals(method.getName())) {
-
if (map.size() == limit) {
-
return "已达容器上线";
-
}
-
System.out.println("Key:" + args[0] + ",Value:" + args[1]);
-
}
-
result = method.invoke(map, args);
-
return result;
-
}
-
-
public static void main(String[] args) {
-
Map<String, String> map = new MapInvocationHandler(3).getInstance();
-
map.put("1", "1");
-
map.put("2", "2");
-
map.put("3", "3");
-
String s = map.put("4", "4");
-
System.out.println(s);
-
}
-
-
}
其中invoke方法中的proxy参数是代理对象。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-776054/
,如需转载,请注明出处,否则将追究法律责任。