golang 每日一庫之 rqlite
rqlite
是一個基於 SQLite 的輕量級、分佈式關係數據庫,旨在提供高可用性和容錯能力。
它是一個 將 SQLite 封裝爲分佈式系統的項目,用 Go 編寫,後端使用 Raft 共識算法實現多節點數據複製與一致性。
地址
GitHub: https://github.com/rqlite/rqlite
文檔: https://rqlite.io
目標
SQLite 是一個嵌入式的、本地文件型數據庫,通常是單機的。
而 rqlite
把 SQLite 封裝爲一個 支持分佈式一致性 的服務,底層通過 Raft 協議(Hashicorp 的 Raft 實現) 來保證多節點之間的數據一致性和故障恢復。
你可以把 rqlite 理解爲:一個小巧、可以跑在樹莓派上的 “高可用 SQLite 集羣”。
功能一覽
架構
+-------------+ +-------------+ +-------------+
| Node A | <----> | Node B | <----> | Node C |
| (Leader) | | (Follower) | | (Follower) |
+-------------+ +-------------+ +-------------+
| | |
+-----------------------------------------------+
| SQLite(嵌入式數據庫,節點本地存儲) |
+-----------------------------------------------+
所有寫入(INSERT/UPDATE/DELETE)通過 Leader 處理,
再複製到其他 Follower 節點,通過 Raft 協議達成一致。
安裝
可以從 GitHub Releases 頁面下載對應平臺的二進制:
curl -L https://github.com/rqlite/rqlite/releases/download/vX.Y.Z/rqlite-vX.Y.Z-linux-amd64.tar.gz | tar -xz
也可以用 Docker:
docker run -p 4001:4001 -p 4002:4002 rqlite/rqlite
啓動一個節點
./rqlited -node-id 1 ~/node.1
默認開啓兩個端口:
-
4001
:HTTP API 端口
-
4002
:Raft 通信端口
加入集羣(啓動更多節點)
./rqlited -node-id 2 -http-addr localhost:4101 -raft-addr localhost:4102 -join http://localhost:4001 ~/node.2
使用 HTTP API 執行 SQL
curl -XPOST -d "CREATE TABLE foo (id INTEGER NOT NULL PRIMARY KEY, name TEXT)" http://localhost:4001/db/execute
curl -XPOST -d "INSERT INTO foo(name) VALUES('bar')" http://localhost:4001/db/execute
curl "http://localhost:4001/db/query?q=SELECT+*+FROM+foo"
結果返回 JSON 格式:
{
"results": [
{
"columns": ["id", "name"],
"types": ["integer", "text"],
"values": [[1, "bar"]]
}
]
}
常見使用場景
-
邊緣計算、IoT 設備分佈式數據同步
-
高可用小型服務的嵌入式數據庫(替代 etcd 或 Consul)
-
開發環境的嵌入式集羣數據庫
-
本地運行、雲端備份的同步型應用
示例
雖然官方未提供 SDK,但你可以通過標準 HTTP 客戶端使用:
package main
import (
"bytes"
"fmt"
"net/http"
)
func main() {
sql := `INSERT INTO foo(name) VALUES("baz")`
res, err := http.Post("http://localhost:4001/db/execute", "application/x-www-form-urlencoded", bytes.NewBuffer([]byte(sql)))
if err != nil {
panic(err)
}
defer res.Body.Close()
fmt.Println("Executed SQL, status:", res.Status)
}
缺陷
-
寫操作需通過 Leader 進行(Follower 只讀)
-
不支持水平擴展(即不支持分片),所有節點的數據是完全一致的
-
不適合高併發大數據寫入(性能受 SQLite 和 Raft 限制)
-
更適合作爲配置中心、輕量級 KV 存儲、分佈式元數據系統
最後
rqlite
是一個 “把 SQLite 升級爲分佈式一致性存儲” 的優秀嘗試,非常適合輕量級、嵌入式、強一致場景。
它不追求大數據處理能力,但在 高可用性、小體積、部署便捷性 等方面有顯著優勢。
"一片葉子落在哪裏都是歸宿,隨緣放下,心安是家。"
標題:golang 每日一庫之 rqlite
作者:mooncakeee
地址:http://blog.dd95828.com/articles/2025/07/04/1751591504036.html
聯繫:scotttu@163.com
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/K1PNpvj2-Qtz0uZya7MRbA