123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- 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 实现
- *
- * <pre>
- *
- * Created by zhenqin.
- * User: zhenqin
- * Date: 2021/7/20
- * Time: 14:46
- * Vendor: yiidata.com
- *
- * </pre>
- *
- * @author zhenqin
- */
- public class LevelDB implements ICache<String>, Closeable {
- /**
- * level db
- */
- final DB db;
- /**
- * KEY 序列化
- */
- private final Serializer<String> 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();
- }
- }
|