Rocksdb 離線生成sst文件並在線加載

rocksdb簡介

RocksDB是Facebook的一個實驗項目,目的是希望能開發一套能在服務器壓力下,真正發揮高速存儲硬件(特別是Flash存儲)性能的高效數據庫系統。這是一個C++庫,允許存儲任意長度二進制kv數據。支持原子讀寫操作。

RocksDB依靠大量靈活的配置,使之能針對不同的生產環境進行調優,包括直接使用內存,使用Flash,使用硬盤或者HDFS。支持使用不同的壓縮算法,並且有一套完整的工具供生產和調試使用。

離線生成sst的意義

我們有億級別的kv數據, 原來是存儲在mongodb中,存儲滿了後,擴容較難,並且每天增量的大數據量寫入會影響現網性能,我們考慮每天增量的數據可以離線寫好生成一個數據文件,線上的kv系統能直接load這個文件。

可以根據預估的數據量,提前計算好需要多少shard,大數據平臺可以根據id將數據hash分片,離線生成好分片數據,查詢時,根據查詢id,計算在那個分片,然後路由服務路由到對應分片去查詢。

這樣的好處:

  • 數據文件可以有版本,在多套環境時,只要加載的數據文件一致,數據就一致
  • 擴容方便,當服務器資源不夠時,直接增加服務器,加載新的分片並將新啓動的服務註冊到配置中心即可
  • 數據寫入都是離線寫入好的,不會影響線上的讀取

當然,對於需要實時寫入的數據,會稍微麻煩點,我們可以考慮Plain+rt方案,提供一個在線實時寫入的小庫,這樣查詢時兩個一起查詢即可,小庫可以定期刷入大庫。

rocksdb 可以離線生成好sst文件,將sst文件拷貝到現網,導入SST文件即可,並且新的sst裏會覆蓋老的同key數據,正好符合我們的需求。

java 生成sst文件

需要先引入maven依賴

<dependency>  
    <groupId>org.rocksdb</groupId>  
    <artifactId>rocksdbjni</artifactId>  
    <version>8.8.1</version>  
</dependency>

然後通過SstFileWriter 創建sst文件寫入即可,需要注意的是,寫入時,Keys must be added in strict ascending order. key需要嚴格遵循字節序。

我們寫一個程序從mongodb讀取數據,並寫入sst。可以先讀取出id,然後按字符串排序。

// SST 寫入,需要按照id排序 Keys must be added in strict ascending order.
Query query = new Query();  
query.fields().include("_id");  
CloseableIterator<Document> dataList = mongoTemplate.stream(query, Document.class, collectionName);

List<String> docIds = new ArrayList<>();  
log.info("start load ids");  
while (dataList.hasNext()) {  
    Document doc = dataList.next();  
    docIds.add(doc.get("_id").toString());  
}  
log.info("load ids finish, start sort id");  
docIds = docIds.stream().sorted().collect(Collectors.toList());

然後根據id從mongo讀取數據,寫入sst



Path sstFile = Paths.get(outputFile);  
EnvOptions env = new EnvOptions();  
Options options = new Options();  
options.setCompressionType(CompressionType.ZSTD_COMPRESSION);  
//        options.setComparator(new MyComparator(new ComparatorOptions()));  
SstFileWriter sst = new SstFileWriter(env, options);  
sst.open(sstFile.toString());  
int count = 0;  
int batchSize = 100;  
int batchCount = docIds.size() / batchSize + 1;  
log.info("batch count is {}", batchCount);  
for (int i = 0; i < batchCount; i++) {  
	if (i * batchCount >= docIds.size()) {  
		break;  
	}  
	List<Long> batchIds = docIds.subList(i * batchCount, Math.min(docIds.size() - 1, (i + 1) * batchCount))  
			.stream().map(Long::parseLong).collect(Collectors.toList());  
	List<Document> batchDocs = mongoTemplate.find(Query.query(Criteria.where("_id").in(batchIds)),  
			Document.class, collectionName);  
	Map<String, Document> docId2Doc = batchDocs.stream().collect(Collectors.toMap(doc -> doc.get("_id").toString(), doc -> doc));  

	for (Long id : batchIds) {  
		String docId = id.toString();  
		Document doc = docId2Doc.get(docId);  
		byte[] value = doc.toJson().getBytes(StandardCharsets.UTF_8);  
		sst.put(docId.getBytes(StandardCharsets.UTF_8), value);  
	}  

	count += batchIds.size();  
	if (count % 10000 == 0) {  
		log.info("already load {} items", count);  
	}  
}  
// 注意一定要finish
sst.finish();  
sst.close();

PS : 上面我們遵循了字節序,如果不想遵循,可以自定義Comparator

class MyComparator extends AbstractComparator {  
  
    protected MyComparator(ComparatorOptions comparatorOptions) {  
        super(comparatorOptions);  
    }  
  
    @Override  
    public String name() {  
        return "MyComparator";  
    }  
  
    @Override  
    public int compare(ByteBuffer byteBuffer, ByteBuffer byteBuffer1) {  
        // always true  
        return 1;  
    }  
}


Options options = new Options();  
options.setCompressionType(CompressionType.ZSTD_COMPRESSION);  
// 使用自定義
options.setComparator(new MyComparator(new ComparatorOptions()));

java 加載sst

可以通過ingestExternalFile 加載sst文件

private static void read(String[] args) {  
  
    String dbFile = args[1];  
    String sstFile = args[2];  
  
  
    // a static method that loads the RocksDB C++ library.  
    RocksDB.loadLibrary();  
  
    // the Options class contains a set of configurable DB options  
    // that determines the behaviour of the database.    try (final Options options = new Options().setCreateIfMissing(true)) {  
  
        options.setCompressionType(CompressionType.ZSTD_COMPRESSION);  
  
        // a factory method that returns a RocksDB instance  
        try (final RocksDB db = RocksDB.open(options, dbFile)) {  
            db.ingestExternalFile(Collections.singletonList(sstFile),new IngestExternalFileOptions());  
  
            while(true) {  
                System.out.print("請輸入查詢key:");  
                String key =  System.console().readLine();  
                byte[] result = db.get(key.getBytes(StandardCharsets.UTF_8));  
                if (result != null) {  
                    System.out.println(new String(result));  
                }  
            }  
        }  
  
  
    } catch (RocksDBException e) {  
        // do some error handling  
        e.printStackTrace();  
    }  
}

golang 加載java生成好的sst

我們已經有一個golang開發的分佈式框架,因此可以java在大數據平臺生成好sst文件,傳輸到現網供go服務load。

golang使用rocksdb,可以使用 "github.com/linxGnu/grocksdb",需要先編譯相關依賴,可以用倉庫中的makefile,make安裝rocksdb等依賴。

然後編譯讀取程序:

package main

import (
	"fmt"
	"os"
	"time"
	
	"github.com/linxGnu/grocksdb"
)

func main() {

	arg := os.Args
	if len(arg) < 3 {
		fmt.Println("Please provide a directory to store the database")
		return
	}

	dir := arg[1]
	fmt.Printf("db dir is %s \n", dir)
	sstFile := arg[2]
	fmt.Printf("sst file is %s \n", sstFile)
	opts := grocksdb.NewDefaultOptions()
	// test the ratelimiter
	rateLimiter := grocksdb.NewRateLimiter(1024, 100*1000, 10)
	opts.SetRateLimiter(rateLimiter)
	opts.SetCreateIfMissing(true)
	// 默認是Snappy。我們相信LZ4總是比Snappy好的。我們之所以把Snappy作爲默認的壓縮方法,是爲了與之前的用戶保持兼容。LZ4/Snappy是輕量壓縮,所以在CPU使用率和存儲空間之間能取得一個較好的平衡
	// 如果你有大量空閒CPU並且希望同時減少空間和寫放大,把options.compression設置爲重量級的壓縮方法。我們推薦ZSTD,如果沒有就用Zlib
	opts.SetCompression(grocksdb.ZSTDCompression)
	db, _ := grocksdb.OpenDb(opts, dir)

	// db.EnableManualCompaction()
	// db.DisableManualCompaction()

	defer db.Close()

	// 合併數據
	ingestOpts := grocksdb.NewDefaultIngestExternalFileOptions()

	err := db.IngestExternalFile([]string{sstFile}, ingestOpts)
	if err != nil {
		fmt.Println("Error ingesting external file:", err)
		return
	}

	fmt.Println("finish IngestExternalFile", time.Now())
	readOpts := grocksdb.NewDefaultReadOptions()

	for {
		var input string
		fmt.Println("請輸入一個查詢key:")
		fmt.Scanln(&input)
		if input == "exit" {
			return
		}
		v1, err := db.Get(readOpts, []byte(input))
		if err != nil {
			fmt.Println("read key error", err)
			continue
		}
		fmt.Println("value = ", string(v1.Data()))

	}
}

編譯時,指定下rocksdb庫的位置。

CGO_CFLAGS="-I/data/grocksdb-1.8.10/dist/linux_amd64/include" CGO_LDFLAGS="-L/data/grocksdb-1.8.10/dist/linux_amd64/lib -lrocksdb -lstdc++ -lm -lz -lsnappy -llz4 -lzstd"   go build -o load_sst_demo ./load_sst_demo.go
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章