Bookeeper基本使用

初始化Bookeeper Client

1
2
3
4
5
6
7
8
9
10
11
12
13

private static final String ZK_ADDR = "127.0.0.1:2181";

try {
//初始化 BookKeeper Client 的方法

BookKeeper bkClient = new BookKeeper(ZK_ADDR);

} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(
"There is an exception throw while creating the BookKeeper client.");
}

创建ledger

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
LedgerHandle longmaoHandler = createLedgerSync(bkClient, "longmaoHandler");

System.out.println("longmaoHandler ledgerId:" + longmaoHandler.getId());

public static LedgerHandle createLedgerSync(BookKeeper bkClient, String pw) {
byte[] password = pw.getBytes();
try {
LedgerHandle handle = bkClient.createLedger(BookKeeper.DigestType.MAC, password);
return handle;
} catch (BKException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}

向Ledger写入数据

1
2
3
4
5
6
7
8
9
10
11
12
13
//添加数据
long maomao = addEntry(longmaoHandler, "maomao");

public static long addEntry(LedgerHandle ledgerHandle, String msg) {
try {
return ledgerHandle.addEntry(msg.getBytes());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BKException e) {
e.printStackTrace();
}
return -1;
}

读取数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//读取数据
Enumeration<LedgerEntry> ledgerEntryEnumeration = readEntry(longmaoHandler);

System.out.println(ledgerEntryEnumeration);
while (ledgerEntryEnumeration.hasMoreElements()) {
LedgerEntry ledgerEntry = ledgerEntryEnumeration.nextElement();
System.out.println("读取数据");
System.out.println(new String(ledgerEntry.getEntry()));
}

public static Enumeration<LedgerEntry> readEntry(LedgerHandle ledgerHandle) {
try {
return ledgerHandle.readEntries(0, ledgerHandle.getLastAddConfirmed());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BKException e) {
e.printStackTrace();
}
return null;
}