maven dependency:
<dependency>
<groupId>org.fusesource.leveldbjni</groupId>
<artifactId>leveldbjni-all</artifactId>
<version>1.8</version>
</dependency>
测试代码实现, 很简单就不多阐述了.
package com.qshuai.singleton;
import org.iq80.leveldb.CompressionType;
import org.iq80.leveldb.DB;
import org.iq80.leveldb.DBIterator;
import org.iq80.leveldb.Options;
import java.io.File;
import java.io.IOException;
import static org.fusesource.leveldbjni.JniDBFactory.asString;
import static org.fusesource.leveldbjni.JniDBFactory.factory;
public class DBTest {
public static void main(String[] args) {
Options utxoOptions = new Options();
utxoOptions.createIfMissing(true);
utxoOptions.compressionType(CompressionType.SNAPPY);
utxoOptions.writeBufferSize(800 * 1048576); // 800MB cache for write buffer
utxoOptions.cacheSize(0);
DB ldb = null;
try {
ldb = factory.open(new File("testdb"), utxoOptions);
} catch (IOException e) {
e.printStackTrace();
}
// less value
ldb.put(("120000" + "00").getBytes(), new byte[2]);
String prefix = "120099";
ldb.put((prefix + "01").getBytes(), new byte[2]);
ldb.put((prefix + "02").getBytes(), new byte[2]);
ldb.put((prefix + "03").getBytes(), new byte[2]);
ldb.put((prefix + "04").getBytes(), new byte[2]);
ldb.put((prefix + "05").getBytes(), new byte[2]);
// great value
ldb.put(("999999" + "00").getBytes(), new byte[2]);
// [first target] to [the last]
System.out.println("[first target] to [the last]");
DBIterator iterator = ldb.iterator();
try {
for (iterator.seek(prefix.getBytes()); iterator.hasNext(); iterator.next()) {
String key = asString(iterator.peekNext().getKey());
String value = asString(iterator.peekNext().getValue());
System.out.println(key + " = " + value);
}
} finally {
}
// [first target] to [last target]
System.out.println("\n[first target] to [last target]");
DBIterator it = ldb.iterator();
try {
for (it.seek(prefix.getBytes()); it.hasNext(); it.next()) {
if (!equalPrefix(it.peekNext().getKey(), prefix.getBytes()))
break;
String key = asString(it.peekNext().getKey());
String value = asString(it.peekNext().getValue());
System.out.println(key + " = " + value);
}
} finally {
}
}
public static boolean equalPrefix(byte[] src, byte[] target) {
if (src.length < target.length)
return false;
for (int i = 0; i <target.length; i++) {
if (src[i] != target[i])
return false;
}
return true;
}
}