Golang文件数据库

最近在学习Golang,想找一个轻量级的文件数据库方案。请问有哪些推荐的Golang文件数据库库?最好是支持JSON格式存储、读写性能不错,并且易于集成的。另外想了解一下这类数据库在实际项目中的使用体验,比如数据量大了之后性能如何?有没有什么需要注意的坑?

2 回复

推荐使用BoltDB或Badger。BoltDB基于B-tree,适合读多写少场景;Badger基于LSM-tree,写性能更优。两者都是Go语言实现的嵌入式键值数据库,无需额外服务,适合轻量级应用。

更多关于Golang文件数据库的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Golang中,文件数据库通常指使用文件系统存储数据的轻量级数据库。常见的实现方式包括:

  1. 键值存储:如使用JSON、Gob或自定义格式存储数据
  2. 嵌入式数据库:如BoltDB(已归档,推荐BoltDB的fork bbolt)或BadgerDB

示例:使用bbolt(键值存储)

package main

import (
	"log"
	"go.etcd.io/bbolt"
)

func main() {
	// 打开数据库文件
	db, err := bbolt.Open("my.db", 0600, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// 创建读写事务
	err = db.Update(func(tx *bbolt.Tx) error {
		// 创建bucket(类似表)
		b, err := tx.CreateBucketIfNotExists([]byte("MyBucket"))
		if err != nil {
			return err
		}
		// 存入键值对
		return b.Put([]byte("answer"), []byte("42"))
	})

	// 读取数据
	db.View(func(tx *bbolt.Tx) error {
		b := tx.Bucket([]byte("MyBucket"))
		v := b.Get([]byte("answer"))
		log.Printf("答案: %s", v)
		return nil
	})
}

示例:使用JSON文件作为数据库

package main

import (
	"encoding/json"
	"os"
)

type Config struct {
	Host string `json:"host"`
	Port int    `json:"port"`
}

func main() {
	// 写入JSON文件
	config := Config{Host: "localhost", Port: 8080}
	file, _ := os.Create("config.json")
	defer file.Close()
	encoder := json.NewEncoder(file)
	encoder.Encode(config)

	// 从JSON文件读取
	file, _ = os.Open("config.json")
	defer file.Close()
	var newConfig Config
	decoder := json.NewDecoder(file)
	decoder.Decode(&newConfig)
}

推荐方案:

  • 需要事务支持:使用 bbolt
  • 高性能需求:考虑 BadgerDB(基于LSM树)
  • 简单配置存储:直接使用JSON/Gob格式文件

注意文件数据库的并发访问需要通过文件锁或数据库自身的事务机制来保证数据一致性。

回到顶部