Java那些事之Berkeley DB
最近一直在使用java,隨著使用時(shí)間的加長(zhǎng),對(duì)java也有了更深入的了解。從今天開(kāi)始,我會(huì)寫(xiě)一些關(guān)于java的專題內(nèi)容,希望大家喜歡,也希望各位多多討論指正。
?
這一次先介紹一下Berkeley DB的java版本,Berkeley DB Java Edition (JE)。
JE 適合于管理海量的,簡(jiǎn)單的數(shù)據(jù)。其中的記錄都以簡(jiǎn)單的鍵值對(duì)保存,即key/value對(duì)。由于它操作簡(jiǎn)單,效率較高,因此受到了廣泛的好評(píng)。下面我就帶領(lǐng)大家看看JE 是如果使用的吧~
JE 下載地址:http://www.oracle.com/technology/software/products/berkeley-db/je/index.html
下載完成解亞后,把JE_HOME/lib/je-.jar 中的jar文件添加到你的環(huán)境變量中就可以使用je了。
相關(guān)幫助文檔可以參考 JE_HOME/docs/index.html
源代碼見(jiàn)JE_HOME/src/*.*
?
?
下面是具體的使用代碼,大家可以參考一下,注釋還是比較詳細(xì)的,有什么不懂的可以給我留言~
?
View Code ?1?//數(shù)據(jù)庫(kù)環(huán)境?2?????private??Environment?myDbEnvironment?=?null;
?3?????//數(shù)據(jù)庫(kù)配置
?4?????private??DatabaseConfig?dbConfig=null;
?5?//????//數(shù)據(jù)庫(kù)游標(biāo)
?6?//????private??Cursor?myCursor?=?null;
?7?????//數(shù)據(jù)庫(kù)對(duì)象
?8?????private??Database?myDatabase?=?null;
?9?????//數(shù)據(jù)庫(kù)文件名
10?????private??String?fileName?=?"";
11?????//數(shù)據(jù)庫(kù)名稱
12?????private??String?dbName?=?""; ?1?????/*
?2??????*?打開(kāi)當(dāng)前數(shù)據(jù)庫(kù)
?3??????*/
?4?????public??void?openDatabase()?{
?5?????????//?TODO?Auto-generated?method?stub
?6?????????try{
?7?????????????CheckMethods.PrintDebugMessage("打開(kāi)數(shù)據(jù)庫(kù):?"+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??????????????*???其他配置?可以進(jìn)行更改
16?????????????????EnvironmentMutableConfig?envMutableConfig?=?new?EnvironmentMutableConfig();
17?????????????????envMutableConfig.setCachePercent(50);//設(shè)置je的cache占用jvm?內(nèi)存的百分比。
18?????????????????envMutableConfig.setCacheSize(123456);//設(shè)定緩存的大小為123456Bytes
19?????????????????envMutableConfig.setTxnNoSync(true);//設(shè)定事務(wù)提交時(shí)是否寫(xiě)更改的數(shù)據(jù)到磁盤(pán),true不寫(xiě)磁盤(pán)。
20?????????????????//envMutableConfig.setTxnWriteNoSync(false);//設(shè)定事務(wù)在提交時(shí),是否寫(xiě)緩沖的log到磁盤(pán)。如果寫(xiě)磁盤(pán)會(huì)影響性能,不寫(xiě)會(huì)影響事務(wù)的安全。隨機(jī)應(yīng)變。
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?設(shè)置用于B?tree比較的比較器,通常是用來(lái)排序
35?????????????????setDuplicateComparator?設(shè)置用來(lái)比較一個(gè)key有兩個(gè)不同值的時(shí)候的大小比較器。
36?????????????????setSortedDuplicates?設(shè)置一個(gè)key是否允許存儲(chǔ)多個(gè)值,true代表允許,默認(rèn)false.
37?????????????????setExclusiveCreate?以獨(dú)占的方式打開(kāi),也就是說(shuō)同一個(gè)時(shí)間只能有一實(shí)例打開(kāi)這個(gè)database。
38?????????????????setReadOnly?以只讀方式打開(kāi)database,默認(rèn)是false.
39?????????????????setTransactional?如果設(shè)置為true,則支持事務(wù)處理,默認(rèn)是false,不支持事務(wù)。
40?????????????*/
41?????????????if(myDatabase?==?null)
42?????????????????myDatabase?=?myDbEnvironment.openDatabase(null,?dbName,?dbConfig);
43?????????????
44?????????????CheckMethods.PrintDebugMessage(dbName+"數(shù)據(jù)庫(kù)中的數(shù)據(jù)個(gè)數(shù):?"+myDatabase.count());
45?????????????/*
46??????????????*??Database.getDatabaseName()
47?????????????????取得數(shù)據(jù)庫(kù)的名稱
48?????????????????如:String?dbName?=?myDatabase.getDatabaseName();
49?????????????????
50?????????????????Database.getEnvironment()
51?????????????????取得包含這個(gè)database的環(huán)境信息
52?????????????????如:Environment?theEnv?=?myDatabase.getEnvironment();
53?????????????????
54?????????????????Database.preload()
55?????????????????預(yù)先加載指定bytes的數(shù)據(jù)到RAM中。
56?????????????????如:myDatabase.preload(1048576l);?//?1024*1024
57?????????????????
58?????????????????Environment.getDatabaseNames()
59?????????????????返回當(dāng)前環(huán)境下的數(shù)據(jù)庫(kù)列表
60?????????????????Environment.removeDatabase()
61?????????????????刪除當(dāng)前環(huán)境中指定的數(shù)據(jù)庫(kù)。
62?????????????????如:
63?????????????????String?dbName?=?myDatabase.getDatabaseName();
64?????????????????myDatabase.close();
65?????????????????myDbEnv.removeDatabase(null,?dbName);
66?????????????????
67?????????????????Environment.renameDatabase()
68?????????????????給當(dāng)前環(huán)境下的數(shù)據(jù)庫(kù)改名
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內(nèi)的所有數(shù)據(jù),返回清空了多少條記錄。
77?????????????????如:
78?????????????????Int?numDiscarded=?myEnv.truncate(null,
79?????????????????myDatabase.getDatabaseName(),true);
80?????????????????CheckMethods.PrintDebugMessage("一共刪除了?"?+?numDiscarded?+"?條記錄?從數(shù)據(jù)庫(kù)?"?+?myDatabase.getDatabaseName());
81??????????????*/
82?????????}
83?????????catch(DatabaseException?e){
84?????????????CheckMethods.PrintInfoMessage(e.getMessage());
85?
86?????????}
87?????}
?
View Code ?1?/*?2??????*?向數(shù)據(jù)庫(kù)中寫(xiě)入記錄
?3??????*?傳入key和value
?4??????*/
?5?????public??boolean?writeToDatabase(String?key,String?value,boolean?isOverwrite)?{
?6?????????//?TODO?Auto-generated?method?stub
?7?????????try?{
?8???????????????//設(shè)置key/value,注意DatabaseEntry內(nèi)使用的是bytes數(shù)組
?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("向數(shù)據(jù)庫(kù)"?+?dbName?+"中寫(xiě)入:"+key+","+value);
30???????????????????????return?true;
31???????????????????}?
32???????????????????else?if(res?==?OperationStatus.KEYEXIST)
33???????????????????{
34???????????????????????CheckMethods.PrintDebugMessage("向數(shù)據(jù)庫(kù)"?+?dbName?+"中寫(xiě)入:"+key+","+value+"失敗,該值已經(jīng)存在");
35???????????????????????return?false;
36???????????????????}
37???????????????????else?
38???????????????????{
39???????????????????????CheckMethods.PrintDebugMessage("向數(shù)據(jù)庫(kù)"?+?dbName?+"中寫(xiě)入:"+key+","+value+"失敗");
40???????????????????????return?false;
41???????????????????}
42???????????????}
43???????????????catch(LockConflictException?lockConflict)
44???????????????{
45???????????????????txn.abort();
46???????????????????CheckMethods.PrintInfoMessage("向數(shù)據(jù)庫(kù)"?+?dbName?+"中寫(xiě)入:"+key+","+value+"出現(xiàn)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?????????????//?錯(cuò)誤處理
56?????????????CheckMethods.PrintInfoMessage("向數(shù)據(jù)庫(kù)"?+?dbName?+"中寫(xiě)入:"+key+","+value+"出現(xiàn)錯(cuò)誤");
57?????????????
58?????????????return?false;
59?????????}
60?????} View Code ?1?/*
?2??????*?關(guān)閉當(dāng)前數(shù)據(jù)庫(kù)
?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("關(guān)閉數(shù)據(jù)庫(kù):?"?+?dbName);
13?????????????myDbEnvironment.cleanLog();?
14?????????????myDbEnvironment.close();
15?????????}
16?????} View Code ?1?/*
?2??????*?刪除數(shù)據(jù)庫(kù)中的一條記錄
?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("從數(shù)據(jù)庫(kù)"?+?dbName?+"中刪除:"+key);
34????????????????????????success?=?true;?
35????????????????????????return?success;
36?????????????????}
37?????????????????else?if(res?==?OperationStatus.KEYEMPTY)
38?????????????????{
39??????????????????????CheckMethods.PrintDebugMessage("沒(méi)有從數(shù)據(jù)庫(kù)"?+?dbName?+"中找到:"+key+"。無(wú)法刪除");
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("刪除操作失敗,出現(xiàn)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??????*?從數(shù)據(jù)庫(kù)中讀出數(shù)據(jù)
?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("從數(shù)據(jù)庫(kù)"?+?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("從數(shù)據(jù)庫(kù)"?+?dbName?+"中讀取:"+key+"出現(xiàn)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??????*?遍歷數(shù)據(jù)庫(kù)中的所有記錄,返回list
?3??????*/
?4?????public??ArrayList<String>?getEveryItem()?{
?5?????????//?TODO?Auto-generated?method?stub
?6?????????CheckMethods.PrintDebugMessage("===========遍歷數(shù)據(jù)庫(kù)"+dbName+"中的所有數(shù)據(jù)==========");
?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方法來(lái)遍歷游標(biāo)獲取數(shù)據(jù)
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處理出現(xiàn)異常");
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?????}
?
?由于考慮到多線程,因此上面的方法都采用了事務(wù),這樣可以很好的保證數(shù)據(jù)的正確性。
?
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/luchen927/archive/2011/06/25/2090400.html
總結(jié)
以上是生活随笔為你收集整理的Java那些事之Berkeley DB的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 泛化背包
- 下一篇: Java读取、创建xml(通过dom方式