Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Template for testing: RocksDB with Scala
import java.io.File
import org.rocksdb._
import org.rocksdb.util.SizeUnit
import scala.collection.JavaConversions._
// build.sbt
// name := "RocksDB"
// version := "0.1"
// scalaVersion := "2.12.0"
// libraryDependencies += "org.rocksdb" % "rocksdbjni" % "5.0.1"
class StoreRocksDB {
val UTF8 : String = "UTF-8"
var isOpen : Boolean = false
val tmpFile = File.createTempFile("rocksdb", ".db")
val tmpFileName = tmpFile.getAbsolutePath
tmpFile.delete
RocksDB.loadLibrary()
var options = new Options().setCreateIfMissing(true)
options.setCreateIfMissing(true)
.createStatistics()
.setWriteBufferSize(200 * SizeUnit.MB)
.setMaxWriteBufferNumber(3)
.setMaxBackgroundCompactions(10)
.setCompressionType(CompressionType.SNAPPY_COMPRESSION)
.setCompactionStyle(CompactionStyle.UNIVERSAL)
// a factory method that returns a RocksDB instance
var store = RocksDB.open(options, tmpFileName )
isOpen = true
def put( k:String , v:String) = {
assert(isOpen)
store.put(
k.getBytes(UTF8),
v.getBytes(UTF8)
)
}
def commit = {}
// if l is sorted by key is better
def putList( l : List[(String,String)])={
assert(isOpen)
val writeOpt = new WriteOptions()
val batch = new WriteBatch()
l.foreach( ll => {
val ( k,v) = ll
batch.put(k.getBytes(UTF8), v.getBytes(UTF8))
})
store.write(writeOpt, batch)
}
def get( k:String) : Option[String]= {
assert(isOpen)
try{
val v = store.get(k.getBytes(UTF8))
Some(new String(v, UTF8))
}catch{
case e:java.lang.NullPointerException => None
}
}
def shutdown = {
store.close()
isOpen = false
tmpFile.delete
}
}
/*
store.store.getProperty("rocksdb.cur-size-all-mem-tables")
store.store.getProperty("rocksdb.estimate-num-keys")
store.store.getProperty("rocksdb.stats")
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment