package com.yiidata.flume.cache; import com.yiidata.flume.cache.serde.Serializer; import com.yiidata.flume.cache.serde.StringSerializer; import com.yiidata.flume.support.FlumeConfig; import lombok.NonNull; import org.iq80.leveldb.DB; import org.iq80.leveldb.Options; import org.iq80.leveldb.impl.Iq80DBFactory; import java.io.Closeable; import java.io.File; import java.io.IOException; /** * * Level DB Cache 实现 * *
 *
 * Created by zhenqin.
 * User: zhenqin
 * Date: 2021/7/20
 * Time: 14:46
 * Vendor: yiidata.com
 *
 * 
* * @author zhenqin */ public class LevelDB implements ICache, Closeable { /** * level db */ final DB db; /** * KEY 序列化 */ private final Serializer KEY_SERDE = new StringSerializer(); public LevelDB() { final File levelDbPath = new File(FlumeConfig.getAppHome(), "db"); if(!levelDbPath.exists()) { levelDbPath.mkdirs(); } try { final Options options = new Options(); options.createIfMissing(true).errorIfExists(false); this.db = new Iq80DBFactory().open(levelDbPath, options); } catch (Exception e) { throw new IllegalStateException(e); } } @Override public void add(@NonNull String key, @NonNull String value) { db.put(KEY_SERDE.serialize(key), KEY_SERDE.serialize(value)); } @Override public void add(String key, int exp, String value) { add(key, value); } @Override public String get(@NonNull String key) { return KEY_SERDE.deserialize(db.get(KEY_SERDE.serialize(key))); } @Override public String remove(@NonNull String key) { db.delete(KEY_SERDE.serialize(key)); return null; } @Override public int removeByPrefix(String prefix) { return 0; } @Override public void clear() { } @Override public int size() { return 0; } @Override public void shutdown() { try { close(); } catch (IOException ignore) {} } @Override public void close() throws IOException { db.close(); } public static void main(String[] args) { final LevelDB levelDB = new LevelDB(); /* for (int i = 0; i < 100000; i++) { levelDB.add("hello" + i, "world, " + i); }*/ long start = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { final String va = levelDB.get("hello" + i); System.out.println(va); } System.out.println(System.currentTimeMillis() - start); /* start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { levelDB.get("hello" + i); } System.out.println(System.currentTimeMillis() - start);*/ levelDB.shutdown(); } }