springboot简单集成RocksDB
pom.xml引入相关依赖
<dependency>
<groupId>org.rocksdb</groupId>
<artifactId>rocksdbjni</artifactId>
<version>6.11.4</version>
</dependency>
复制代码
yml配置RocksDB数据库位置
rocksDB:
path: D:\RocksDBData
复制代码
配置类实例化RocksDB
import org.rocksdb.Options;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* ===========================
* Created By IntelliJ IDEA
* 实例化rocksDB数据库
* @author Lei
* @date 2020-09-25 11:08
* ===========================
*/
@Configuration
@EnableAutoConfiguration
public class MyRocksDB {
@Value("${rocksDB.path}")
private String rocksDBDataPath;
@Bean
public RocksDB getRocksDB() {
try {
RocksDB.loadLibrary();
Options options = new Options();
options.setCreateIfMissing(true);
return RocksDB.open(options, rocksDBDataPath);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
复制代码
RocksDB操作接口
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
/**
* ===========================
* Created By IntelliJ IDEA
*
* @author Lei
* @date 2020-09-25 15:13
* ===========================
*/
public interface MyRocksDbService {
/**
* @param data 要保存的数据
* 保存数据到RocksDB
* */
void save(Map<String, Object> data);
/*
* @param key
* 根据key获取数据
* */
JSONObject get(String key);
}
复制代码
RocksDB操作实现类
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icreate.esb.service.MyRocksDbService;
import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* ===========================
* Created By IntelliJ IDEA
*
* @author Lei
* @date 2020-09-25 15:47
* ===========================
*/
@Service("/myRocksDbService")
public class MyRocksDbServiceImpl implements MyRocksDbService {
@Autowired
private RocksDB rocksDB;
@Override
public void save(Map<String, Object> data) {
try {
rocksDB.put(((String)data.get("rocksDbKey")).getBytes(), JSON.toJSONString(data).getBytes());
} catch (RocksDBException e) {
e.printStackTrace();
}
}
@Override
public JSONObject get(String key) {
try {
byte[] value = rocksDB.get(key.getBytes());
return JSON.parseObject(new String(value));
} catch (RocksDBException e) {
e.printStackTrace();
}
return null;
}
}
相关文章