【Mybatis】FIFO缓冲实现
FIFO (first in, first out) 即“先进先出”缓冲淘汰算法。
Cache 接口定义
public interface Cache {
/**
* 缓冲 ID
*/
String getId();
/**
* 存储数据
*/
void putObject(Object key, Object value);
/**
* 获取数据
*/
Object getObject(Object key);
/**
* 删除数据
*/
Object removeObject(Object key);
/**
* 清空缓冲
*/
void clear();
/**
* 获取缓冲大小
*/
int getSize();
ReadWriteLock getReadWriteLock();
}
FIFOCache 实现类
FIFOCache 实现 Cache 接口
package org.apache.ibatis.cache.decorators;
import java.util.Deque;
import java.util.LinkedList;
import java.util.concurrent.locks.ReadWriteLock;
import org.apache.ibatis.cache.Cache;
/**
* FIFO (first in, first out) cache decorator
*/
public class FifoCache implements Cache {
private final Cache delegate;
private final Deque<Object> keyList;
private int size;
public FifoCache(Cache delegate) {
this.delegate = delegate;
this.keyList = new LinkedList<Object>();
this.size = 1024;
}
@Override
public String getId() {
return delegate.getId();
}
@Override
public int getSize() {
return delegate.getSize();
}
public void setSize(int size) {
this.size = size;
}
@Override
public void putObject(Object key, Object value) {
cycleKeyList(key);
delegate.putObject(key, value);
}
@Override
public Object getObject(Object key) {
return delegate.getObject(key);
}
@Override
public Object removeObject(Object key) {
return delegate.removeObject(key);
}
@Override
public void clear() {
delegate.clear();
keyList.clear();
}
@Override
public ReadWriteLock getReadWriteLock() {
return null;
}
private void cycleKeyList(Object key) {
keyList.addLast(key);
if (keyList.size() > size) {
Object oldestKey = keyList.removeFirst();
delegate.removeObject(oldestKey);
}
}
}