手写一个简版的Redis,实现高性能的key/value服务
阅读本文大概需要 3 分钟。
来自:网络
前言
RocksDB
特征
RestExpress
实现kedis
/**
* @author: kl @kailing.pub
* @date: 2019/4/12
*/
public class Main {
public static void main(String[] args) {
Configs configs = new Configs();
configs.fromArgs(args);
RestExpress server = new RestExpress()
.setName("kedis-server")
.setBaseUrl("http://localhost:" +configs.getPort());
KedisCore core =new KedisCore(configs.getDbPath());
Routes.define(server,core);
server.bind(configs.getPort());
server.awaitShutdown();
}
}
创建RocksDB引擎api操作类
/**
* @author: kl @kailing.pub
* @date: 2019/4/12
*/
public class KedisCore {
private RocksDB db;
public KedisCore(String path) {
RocksDB.loadLibrary();
try {
final Options options = new Options().setCreateIfMissing(true);
this.db = RocksDB.open(options, path);
} catch (RocksDBException ex) {
ex.printStackTrace();
}
}
public String put(Request request, Response response) throws Exception {
Map<String, String> map = request.getQueryStringMap();
String key = map.get("key");
String value = map.get("value");
db.put(key.getBytes(), value.getBytes());
return "ok";
}
public String get(Request request, Response response) throws Exception {
Map<String, String> map = request.getQueryStringMap();
String key = map.get("key");
byte[] values = db.get(key.getBytes());
if(values != null){
return new String(values,"utf-8");
}else {
return null;
}
}
}
设置请求路由
/**
* @author: kl @kailing.pub
* @date: 2019/4/12
*/
public abstract class Routes {
public static void define(RestExpress server,KedisCore core){
server.uri("/put", core).action("put", HttpMethod.GET).noSerialization();
server.uri("/get", core).action("get", HttpMethod.GET).noSerialization();
}
}
启动
java -jar kedis-1.0.jar --port 8081
插入数据
curl http://localhost:8081/put?key=name&value=ckl
获取数据
curl http://localhost:8081/get?key=name
文末结语
微信扫描二维码,关注我的公众号
朕已阅