Java那些事之Berkeley DB
生活随笔
收集整理的這篇文章主要介紹了
Java那些事之Berkeley DB
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近一直在使用java,隨著使用時間的加長,對java也有了更深入的了解。從今天開始,我會寫一些關于java的專題內容,希望大家喜歡,也希望各位多多討論指正。
?
這一次先介紹一下Berkeley DB的java版本,Berkeley DB Java Edition (JE)。
JE 適合于管理海量的,簡單的數據。其中的記錄都以簡單的鍵值對保存,即key/value對。由于它操作簡單,效率較高,因此受到了廣泛的好評。下面我就帶領大家看看JE 是如果使用的吧~
JE 下載地址:http://www.oracle.com/technology/software/products/berkeley-db/je/index.html
下載完成解亞后,把JE_HOME/lib/je-.jar 中的jar文件添加到你的環境變量中就可以使用je了。
相關幫助文檔可以參考 JE_HOME/docs/index.html
源代碼見JE_HOME/src/*.*
?
?
下面是具體的使用代碼,大家可以參考一下,注釋還是比較詳細的,有什么不懂的可以給我留言~
?
View Code ?1?//數據庫環境?2?????private??Environment?myDbEnvironment?=?null;
?3?????//數據庫配置
?4?????private??DatabaseConfig?dbConfig=null;
?5?//????//數據庫游標
?6?//????private??Cursor?myCursor?=?null;
?7?????//數據庫對象
?8?????private??Database?myDatabase?=?null;
?9?????//數據庫文件名
10?????private??String?fileName?=?"";
11?????//數據庫名稱
12?????private??String?dbName?=?""; ?1?????/*
?2??????*?打開當前數據庫
?3??????*/
?4?????public??void?openDatabase()?{
?5?????????//?TODO?Auto-generated?method?stub
?6?????????try{
?7?????????????CheckMethods.PrintDebugMessage("打開數據庫:?"+dbName);
?8?????????????EnvironmentConfig?envConfig?=?new?EnvironmentConfig();
?9?????????????envConfig.setAllowCreate(true);
10?????????????envConfig.setTransactional(true);
11?????????????envConfig.setReadOnly(false);
12?????????????envConfig.setTxnTimeout(10000,?TimeUnit.MILLISECONDS);
13?????????????envConfig.setLockTimeout(10000,?TimeUnit.MILLISECONDS);
14?????????????/*
15??????????????*???其他配置?可以進行更改
16?????????????????EnvironmentMutableConfig?envMutableConfig?=?new?EnvironmentMutableConfig();
17?????????????????envMutableConfig.setCachePercent(50);//設置je的cache占用jvm?內存的百分比。
18?????????????????envMutableConfig.setCacheSize(123456);//設定緩存的大小為123456Bytes
19?????????????????envMutableConfig.setTxnNoSync(true);//設定事務提交時是否寫更改的數據到磁盤,true不寫磁盤。
20?????????????????//envMutableConfig.setTxnWriteNoSync(false);//設定事務在提交時,是否寫緩沖的log到磁盤。如果寫磁盤會影響性能,不寫會影響事務的安全。隨機應變。
21??????????????*
22??????????????*/
23?????????????File?file?=?new?File(fileName);
24?????????????if(!file.exists())
25?????????????????file.mkdirs();
26?????????????myDbEnvironment?=?new?Environment(file,envConfig);
27?????????????
28?????????????dbConfig?=?new?DatabaseConfig();
29?????????????dbConfig.setAllowCreate(true);
30?????????????dbConfig.setTransactional(true);
31?????????????dbConfig.setReadOnly(false);
32?????????????//dbConfig.setSortedDuplicates(false);
33?????????????/*
34?????????????????setBtreeComparator?設置用于B?tree比較的比較器,通常是用來排序
35?????????????????setDuplicateComparator?設置用來比較一個key有兩個不同值的時候的大小比較器。
36?????????????????setSortedDuplicates?設置一個key是否允許存儲多個值,true代表允許,默認false.
37?????????????????setExclusiveCreate?以獨占的方式打開,也就是說同一個時間只能有一實例打開這個database。
38?????????????????setReadOnly?以只讀方式打開database,默認是false.
39?????????????????setTransactional?如果設置為true,則支持事務處理,默認是false,不支持事務。
40?????????????*/
41?????????????if(myDatabase?==?null)
42?????????????????myDatabase?=?myDbEnvironment.openDatabase(null,?dbName,?dbConfig);
43?????????????
44?????????????CheckMethods.PrintDebugMessage(dbName+"數據庫中的數據個數:?"+myDatabase.count());
45?????????????/*
46??????????????*??Database.getDatabaseName()
47?????????????????取得數據庫的名稱
48?????????????????如:String?dbName?=?myDatabase.getDatabaseName();
49?????????????????
50?????????????????Database.getEnvironment()
51?????????????????取得包含這個database的環境信息
52?????????????????如:Environment?theEnv?=?myDatabase.getEnvironment();
53?????????????????
54?????????????????Database.preload()
55?????????????????預先加載指定bytes的數據到RAM中。
56?????????????????如:myDatabase.preload(1048576l);?//?1024*1024
57?????????????????
58?????????????????Environment.getDatabaseNames()
59?????????????????返回當前環境下的數據庫列表
60?????????????????Environment.removeDatabase()
61?????????????????刪除當前環境中指定的數據庫。
62?????????????????如:
63?????????????????String?dbName?=?myDatabase.getDatabaseName();
64?????????????????myDatabase.close();
65?????????????????myDbEnv.removeDatabase(null,?dbName);
66?????????????????
67?????????????????Environment.renameDatabase()
68?????????????????給當前環境下的數據庫改名
69?????????????????如:
70?????????????????String?oldName?=?myDatabase.getDatabaseName();??
71?????????????????String?newName?=?new?String(oldName?+?".new",?"UTF-8");
72?????????????????myDatabase.close();
73?????????????????myDbEnv.renameDatabase(null,?oldName,?newName);
74?????????????????
75?????????????????Environment.truncateDatabase()
76?????????????????清空database內的所有數據,返回清空了多少條記錄。
77?????????????????如:
78?????????????????Int?numDiscarded=?myEnv.truncate(null,
79?????????????????myDatabase.getDatabaseName(),true);
80?????????????????CheckMethods.PrintDebugMessage("一共刪除了?"?+?numDiscarded?+"?條記錄?從數據庫?"?+?myDatabase.getDatabaseName());
81??????????????*/
82?????????}
83?????????catch(DatabaseException?e){
84?????????????CheckMethods.PrintInfoMessage(e.getMessage());
85?
86?????????}
87?????}
?
View Code ?1?/*?2??????*?向數據庫中寫入記錄
?3??????*?傳入key和value
?4??????*/
?5?????public??boolean?writeToDatabase(String?key,String?value,boolean?isOverwrite)?{
?6?????????//?TODO?Auto-generated?method?stub
?7?????????try?{
?8???????????????//設置key/value,注意DatabaseEntry內使用的是bytes數組
?9???????????????DatabaseEntry?theKey=new?DatabaseEntry(StringHelper.TrimString(key).getBytes("UTF-8"));
10???????????????DatabaseEntry?theData=new?DatabaseEntry(value.getBytes("UTF-8"));
11???????????????OperationStatus?res?=?null;
12???????????????Transaction?txn?=?null;
13???????????????try
14???????????????{
15???????????????????TransactionConfig?txConfig?=?new?TransactionConfig();
16???????????????????txConfig.setSerializableIsolation(true);
17???????????????????txn?=?myDbEnvironment.beginTransaction(null,?txConfig);
18???????????????????if(isOverwrite)
19???????????????????{
20???????????????????????res?=?myDatabase.put(txn,?theKey,?theData);
21???????????????????}
22???????????????????else
23???????????????????{
24???????????????????????res?=?myDatabase.putNoOverwrite(txn,?theKey,?theData);
25???????????????????}
26???????????????????txn.commit();
27???????????????????if(res?==?OperationStatus.SUCCESS)
28???????????????????{
29???????????????????????CheckMethods.PrintDebugMessage("向數據庫"?+?dbName?+"中寫入:"+key+","+value);
30???????????????????????return?true;
31???????????????????}?
32???????????????????else?if(res?==?OperationStatus.KEYEXIST)
33???????????????????{
34???????????????????????CheckMethods.PrintDebugMessage("向數據庫"?+?dbName?+"中寫入:"+key+","+value+"失敗,該值已經存在");
35???????????????????????return?false;
36???????????????????}
37???????????????????else?
38???????????????????{
39???????????????????????CheckMethods.PrintDebugMessage("向數據庫"?+?dbName?+"中寫入:"+key+","+value+"失敗");
40???????????????????????return?false;
41???????????????????}
42???????????????}
43???????????????catch(LockConflictException?lockConflict)
44???????????????{
45???????????????????txn.abort();
46???????????????????CheckMethods.PrintInfoMessage("向數據庫"?+?dbName?+"中寫入:"+key+","+value+"出現lock異常");
47???????????????????CheckMethods.PrintInfoMessage(lockConflict.getMessage());
48???????????????????CheckMethods.PrintInfoMessage(lockConflict.getCause().toString());
49???????????????????CheckMethods.PrintInfoMessage(lockConflict.getStackTrace().toString());
50?????????????????????????????????return?false;
51???????????????}
52?????????}
53?????????catch?(Exception?e)?
54?????????{
55?????????????//?錯誤處理
56?????????????CheckMethods.PrintInfoMessage("向數據庫"?+?dbName?+"中寫入:"+key+","+value+"出現錯誤");
57?????????????
58?????????????return?false;
59?????????}
60?????} View Code ?1?/*
?2??????*?關閉當前數據庫
?3??????*/
?4?????public??void?closeDatabase()?{
?5?????????//?TODO?Auto-generated?method?stub????
?6?????????if(myDatabase?!=?null)
?7?????????{
?8?????????????myDatabase.close();
?9?????????}
10?????????if(myDbEnvironment?!=?null)
11?????????{
12?????????????CheckMethods.PrintDebugMessage("關閉數據庫:?"?+?dbName);
13?????????????myDbEnvironment.cleanLog();?
14?????????????myDbEnvironment.close();
15?????????}
16?????} View Code ?1?/*
?2??????*?刪除數據庫中的一條記錄
?3??????*/
?4?????public??boolean?deleteFromDatabase(String?key)?{
?5?????????boolean?success?=?false;
?6????????????long?sleepMillis?=?0;
?7?????????for(int?i=0;i<3;i++)
?8?????????{
?9?????????????if?(sleepMillis?!=?0)?
10?????????????{
11?????????????????try?
12?????????????????{
13?????????????????????Thread.sleep(sleepMillis);
14?????????????????}?
15?????????????????catch?(InterruptedException?e)?
16?????????????????{
17?????????????????????e.printStackTrace();
18?????????????????}
19?????????????????sleepMillis?=?0;
20?????????????}
21?????????????Transaction?txn?=?null;
22?????????????try
23?????????????{
24?????????????????TransactionConfig?txConfig?=?new?TransactionConfig();
25?????????????????txConfig.setSerializableIsolation(true);
26?????????????????txn?=?myDbEnvironment.beginTransaction(null,?txConfig);
27?????????????????DatabaseEntry?theKey;
28?????????????????theKey?=?new?DatabaseEntry(StringHelper.TrimString(key).getBytes("UTF-8"));
29?????????????????OperationStatus?res?=?myDatabase.delete(txn,?theKey);
30?????????????????txn.commit();
31?????????????????if(res?==?OperationStatus.SUCCESS)
32?????????????????{
33??????????????????????CheckMethods.PrintDebugMessage("從數據庫"?+?dbName?+"中刪除:"+key);
34????????????????????????success?=?true;?
35????????????????????????return?success;
36?????????????????}
37?????????????????else?if(res?==?OperationStatus.KEYEMPTY)
38?????????????????{
39??????????????????????CheckMethods.PrintDebugMessage("沒有從數據庫"?+?dbName?+"中找到:"+key+"。無法刪除");
40?????????????????}
41?????????????????else
42?????????????????{
43??????????????????????CheckMethods.PrintDebugMessage("刪除操作失敗,由于"+res.toString());
44?????????????????}
45?????????????????return?false;
46?????????????}
47?????????????catch?(UnsupportedEncodingException?e)?
48?????????????{
49?????????????????//?TODO?Auto-generated?catch?block
50?????????????????
51?????????????????e.printStackTrace();
52?????????????????return?false;
53?????????????}
54?????????????catch(LockConflictException?lockConflict)
55?????????????{
56?????????????????CheckMethods.PrintInfoMessage("刪除操作失敗,出現lockConflict異常");
57?????????????????CheckMethods.PrintInfoMessage(lockConflict.getMessage());
58?????????????????CheckMethods.PrintInfoMessage(lockConflict.getCause().toString());
59?????????????????CheckMethods.PrintInfoMessage(lockConflict.getStackTrace().toString());
60?????????????????sleepMillis?=?1000;
61?????????????????
62?????????????????continue;
63?????????????}
64?????????????finally?
65?????????????{
66??????????????????if?(!success)
67??????????????????{
68???????????????????????if?(txn?!=?null)?
69???????????????????????{
70???????????????????????????txn.abort();
71???????????????????????}
72??????????????????}
73?????????????}
74?????????}
75?????????return?false;
76?????} View Code ?1?????/*
?2??????*?從數據庫中讀出數據
?3??????*?傳入key?返回value
?4??????*/
?5?????public?String?readFromDatabase(String?key)?{
?6?????????//?TODO?Auto-generated?method?stub
?7?????????//Database.getSearchBoth()
?8?????????try?{
?9??????????????DatabaseEntry?theKey?=?new?DatabaseEntry(StringHelper.TrimString(key).getBytes("UTF-8"));
10??????????????DatabaseEntry?theData?=?new?DatabaseEntry();
11??????????????Transaction?txn?=?null;
12??????????????try
13??????????????{
14??????????????????TransactionConfig?txConfig?=?new?TransactionConfig();
15??????????????????txConfig.setSerializableIsolation(true);
16??????????????????txn?=?myDbEnvironment.beginTransaction(null,?txConfig);
17??????????????????OperationStatus?res?=?myDatabase.get(txn,?theKey,?theData,?LockMode.DEFAULT);
18??????????????????txn.commit();
19??????????????????if(res?==?OperationStatus.SUCCESS)
20??????????????????{
21??????????????????????byte[]?retData?=?theData.getData();
22??????????????????????String?foundData?=?new?String(retData,?"UTF-8");
23??????????????????????CheckMethods.PrintDebugMessage("從數據庫"?+?dbName?+"中讀取:"+key+","+foundData);
24??????????????????????return?foundData;
25??????????????????}
26??????????????????else
27??????????????????{
28??????????????????????CheckMethods.PrintDebugMessage("No?record?found?for?key?'"?+?key?+?"'.");
29??????????????????????return?"";
30??????????????????}
31??????????????}
32??????????????catch(LockConflictException?lockConflict)
33??????????????{
34??????????????????txn.abort();
35??????????????????CheckMethods.PrintInfoMessage("從數據庫"?+?dbName?+"中讀取:"+key+"出現lock異常");
36??????????????????CheckMethods.PrintInfoMessage(lockConflict.getMessage());
37??????????????????CheckMethods.PrintInfoMessage(lockConflict.getCause().toString());
38??????????????????CheckMethods.PrintInfoMessage(lockConflict.getStackTrace().toString());
39??????????????????
40??????????????????return?"";
41??????????????}
42?????????????
43?????????}?catch?(UnsupportedEncodingException?e)?{
44?????????????//?TODO?Auto-generated?catch?block
45?????????????e.printStackTrace();
46?????????????
47?????????????return?"";
48?????????}
49?????} View Code ?1?/*
?2??????*?遍歷數據庫中的所有記錄,返回list
?3??????*/
?4?????public??ArrayList<String>?getEveryItem()?{
?5?????????//?TODO?Auto-generated?method?stub
?6?????????CheckMethods.PrintDebugMessage("===========遍歷數據庫"+dbName+"中的所有數據==========");
?7??????????Cursor?myCursor?=?null;
?8??????????ArrayList<String>?resultList?=?new?ArrayList<String>();
?9??????????Transaction?txn?=?null;
10??????????try{
11??????????????txn?=?this.myDbEnvironment.beginTransaction(null,?null);
12??????????????CursorConfig?cc?=?new?CursorConfig();
13??????????????cc.setReadCommitted(true);
14??????????????if(myCursor==null)
15??????????????????myCursor?=?myDatabase.openCursor(txn,?cc);
16??????????????DatabaseEntry?foundKey?=?new?DatabaseEntry();
17??????????????DatabaseEntry?foundData?=?new?DatabaseEntry();?????????
18??????????????//?使用cursor.getPrev方法來遍歷游標獲取數據
19??????????????if(myCursor.getFirst(foundKey,?foundData,?LockMode.DEFAULT)
20??????????????????????==?OperationStatus.SUCCESS)
21??????????????{
22??????????????????String?theKey?=?new?String(foundKey.getData(),?"UTF-8");
23??????????????????String?theData?=?new?String(foundData.getData(),?"UTF-8");
24??????????????????resultList.add(theKey);
25??????????????????CheckMethods.PrintDebugMessage("Key?|?Data?:?"?+?theKey?+?"?|?"?+?theData?+?"");
26??????????????????while?(myCursor.getNext(foundKey,?foundData,?LockMode.DEFAULT)?
27????????????????????????????==?OperationStatus.SUCCESS)?
28??????????????????{
29?????????????????????????theKey?=?new?String(foundKey.getData(),?"UTF-8");
30?????????????????????????theData?=?new?String(foundData.getData(),?"UTF-8");
31?????????????????????????resultList.add(theKey);
32?????????????????????????CheckMethods.PrintDebugMessage("Key?|?Data?:?"?+?theKey?+?"?|?"?+?theData?+?"");
33??????????????????}
34??????????????}
35??????????????myCursor.close();
36??????????????txn.commit();
37??????????????return?resultList;
38??????????}?
39??????????catch?(UnsupportedEncodingException?e)?{
40?????????????//?TODO?Auto-generated?catch?block
41?????????????e.printStackTrace();????
42?????????????return?null;
43??????????}
44??????????catch?(Exception?e)?
45??????????{
46??????????????CheckMethods.PrintInfoMessage("getEveryItem處理出現異常");
47??????????????CheckMethods.PrintInfoMessage(e.getMessage().toString());
48??????????????CheckMethods.PrintInfoMessage(e.getCause().toString());
49??????????????
50??????????????txn.abort();
51??????????????if?(myCursor?!=?null)?
52??????????????{
53??????????????????myCursor.close();
54??????????????}
55??????????????return?null;
56??????????}
57?????}
?
?由于考慮到多線程,因此上面的方法都采用了事務,這樣可以很好的保證數據的正確性。
?
?
?
?
轉載于:https://www.cnblogs.com/luchen927/archive/2011/06/25/2090400.html
總結
以上是生活随笔為你收集整理的Java那些事之Berkeley DB的全部內容,希望文章能夠幫你解決所遇到的問題。