public class RefreshFilter implements ActionFilter {
@Override
public View match(ActionContext actionContext) {
HttpServletRequest request = actionContext.getRequest();
String requestURI = request.getRequestURI();
Cache cache = Cache.getInstance();
cache.increment(requestURI);
if (cache.isUpCount(requestURI)) {
throw new ServiceException("网络忙,请稍候再试!");
}
return null;
}
// 缓存
private static class Cache {
private static final ConcurrentHashMap<String, CopyOnWriteArrayList<Long>> map = new ConcurrentHashMap<String, CopyOnWriteArrayList<Long>>();
private static final long EXPIRE_TIME = 1000 * 10L;
private static final long CLEAR_TIME = 1000 * 2L;
private static final int MAX_REFRESH_COUNT = 5;
private static final Cache cache = new Cache();
private Cache() {
new Thread(new ClearCacheRunnable()).start();
}
public static Cache getInstance() {
return cache;
}
// 增长指定URL的点击次数
public void increment(String key) {
CopyOnWriteArrayList<Long> list = map.get(key);
if (list == null) {
map.put(key, new CopyOnWriteArrayList<Long>());
}
map.get(key).add(new Long(System.currentTimeMillis()));
}
// 是否到达指定数量
public boolean isUpCount(String key) {
CopyOnWriteArrayList<Long> list = map.get(key);
if (list == null) {
return false;
}
return list.size() > MAX_REFRESH_COUNT;
}
// 清理过期数据线程
private static class ClearCacheRunnable implements Runnable {
@Override
public void run() {
while (true) {
try {
Thread.sleep(Cache.CLEAR_TIME);
clear();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void clear() {
for (String key : map.keySet()) {
CopyOnWriteArrayList<Long> list = map.get(key);
for (Long date : list) {
if (System.currentTimeMillis() - date > Cache.EXPIRE_TIME) {
System.out.println(list.remove(date));
}
}
}
}
}
}
}