/**
* 封装对Berkeley DB一般操作的抽象类
* **/
public abstract class AbstractFrontier {
private Environment env;
private static final String CLASS_CATALOG = "java_class_catalog";
protected StoredClassCatalog javaCatalog;
protected Database catalogdatabase;
protected Database database;
public AbstractFrontier(String homeDirectory) throws DatabaseException, FileNotFoundException {
EnvironmentConfig envConfig = new EnvironmentConfig(); // 打开env
envConfig.setTransactional(true);
envConfig.setAllowCreate(true);
env = new Environment(new File(homeDirectory), envConfig);
DatabaseConfig dbConfig = new DatabaseConfig(); // 设置DatabaseConfig
dbConfig.setTransactional(true);
dbConfig.setAllowCreate(true);
catalogdatabase = env.openDatabase(null, CLASS_CATALOG, dbConfig); // 打开
javaCatalog = new StoredClassCatalog(catalogdatabase);
database = env.openDatabase(null, "URL", dbConfig); // 打开
}
//关闭数据库,关闭环境
public void close() throws DatabaseException {
database.close();
javaCatalog.close();
env.close();
}
//put方法
protected abstract void put(Object key,Object value);
//get方法
protected abstract Object get(Object key);
//delete方法
protected abstract Object delete(Object key);
}
public class BDBFrontier extends AbstractFrontier {
@SuppressWarnings("unchecked")
private StoredMap pendingUrisDB = null;
//使用默认的路径和缓存大小构造函数
public BDBFrontier(String homeDirectory) throws DatabaseException, FileNotFoundException{
super(homeDirectory);
EntryBinding<String> keyBinding = new SerialBinding<String>(javaCatalog, String.class);
EntryBinding<String> valueBinding = new SerialBinding<String>(javaCatalog, String.class);
pendingUrisDB = new StoredMap<String, String>(database, keyBinding, valueBinding, true);
}
// 底层存入数据库
@SuppressWarnings("unchecked")
public void put(Object key, Object value) {
pendingUrisDB.put(key, value);
}
//取出
public Object get(Object key){
return pendingUrisDB.get(key);
}
//删除
public Object delete(Object key){
return pendingUrisDB.remove(key);
}
//是否包含key
public boolean containKey(Object key){
return pendingUrisDB.containsKey(key);
}
//得到keySet
@SuppressWarnings("unchecked")
public Set<String> getKeySet(){
return pendingUrisDB.keySet();
}
// 测试函数
public static void main(String[] strs) throws Exception {
BDBFrontier bDBFrontier = new BDBFrontier("E:\\BerkeleyDB");
for (int i = 0; i < 30; i++) {
bDBFrontier.put("www" + i, "http://" + i);
}
Set<String> set = bDBFrontier.getKeySet();
for (String Str : set) {
System.out.println(Str);
}
bDBFrontier.close();
}
}