插件窝 干货文章 Linux平台上Golang如何进行数据存储

Linux平台上Golang如何进行数据存储

err panic nil 存储 407    来源:    2025-05-09

Golang在Linux平台上的数据存储方案

在Linux平台上使用Golang进行数据存储有多种选择,以下是主要的几种方案及其实现方法:

1. 文件系统存储

基本文件操作

import (
    "os"
    "io/ioutil"
)

// 写入文件
err := ioutil.WriteFile("data.txt", []byte("Hello, World!"), 0644)
if err != nil {
    panic(err)
}

// 读取文件
data, err := ioutil.ReadFile("data.txt")
if err != nil {
    panic(err)
}
fmt.Println(string(data))

更高效的文件操作

import "bufio"

// 缓冲写入
file, err := os.Create("data.txt")
if err != nil {
    panic(err)
}
defer file.Close()

writer := bufio.NewWriter(file)
_, err = writer.WriteString("Buffered data\n")
if err != nil {
    panic(err)
}
writer.Flush()

2. 关系型数据库 (SQL)

使用database/sql包

import (
    "database/sql"
    _ "github.com/lib/pq" // PostgreSQL驱动
    // _ "github.com/go-sql-driver/mysql" // MySQL驱动
)

// 连接数据库
db, err := sql.Open("postgres", "user=postgres dbname=test sslmode=disable")
if err != nil {
    panic(err)
}
defer db.Close()

// 创建表
_, err = db.Exec(`CREATE TABLE IF NOT EXISTS users (
    id SERIAL PRIMARY KEY,
    name TEXT,
    email TEXT
)`)
if err != nil {
    panic(err)
}

// 插入数据
_, err = db.Exec("INSERT INTO users (name, email) VALUES ($1, $2)", "Alice", "alice@example.com")
if err != nil {
    panic(err)
}

// 查询数据
rows, err := db.Query("SELECT id, name, email FROM users")
if err != nil {
    panic(err)
}
defer rows.Close()

for rows.Next() {
    var id int
    var name, email string
    err = rows.Scan(&id, &name, &email)
    if err != nil {
        panic(err)
    }
    fmt.Println(id, name, email)
}

3. NoSQL数据库

MongoDB

import (
    "context"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

// 连接MongoDB
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
    panic(err)
}
defer client.Disconnect(context.TODO())

// 获取集合
collection := client.Database("test").Collection("users")

// 插入文档
_, err = collection.InsertOne(context.TODO(), bson.M{"name": "Bob", "email": "bob@example.com"})
if err != nil {
    panic(err)
}

// 查询文档
cursor, err := collection.Find(context.TODO(), bson.M{})
if err != nil {
    panic(err)
}
defer cursor.Close(context.TODO())

for cursor.Next(context.TODO()) {
    var result bson.M
    err := cursor.Decode(&result)
    if err != nil {
        panic(err)
    }
    fmt.Println(result)
}

Redis

import (
    "github.com/go-redis/redis/v8"
    "context"
)

// 连接Redis
rdb := redis.NewClient(&redis.Options{
    Addr:     "localhost:6379",
    Password: "", // 无密码
    DB:       0,  // 默认DB
})

ctx := context.Background()

// 设置键值
err := rdb.Set(ctx, "key", "value", 0).Err()
if err != nil {
    panic(err)
}

// 获取值
val, err := rdb.Get(ctx, "key").Result()
if err != nil {
    panic(err)
}
fmt.Println("key", val)

4. 嵌入式数据库

SQLite

import (
    "database/sql"
    _ "github.com/mattn/go-sqlite3"
)

// 打开或创建SQLite数据库
db, err := sql.Open("sqlite3", "./test.db")
if err != nil {
    panic(err)
}
defer db.Close()

// 使用方式与其它SQL数据库类似

BoltDB (键值存储)

import (
    "github.com/boltdb/bolt"
    "log"
)

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

// 创建bucket并存储数据
err = db.Update(func(tx *bolt.Tx) error {
    b, err := tx.CreateBucketIfNotExists([]byte("MyBucket"))
    if err != nil {
        return err
    }
    return b.Put([]byte("answer"), []byte("42"))
})
if err != nil {
    panic(err)
}

// 读取数据
err = db.View(func(tx *bolt.Tx) error {
    b := tx.Bucket([]byte("MyBucket"))
    v := b.Get([]byte("answer"))
    fmt.Printf("The answer is: %s\n", v)
    return nil
})
if err != nil {
    panic(err)
}

5. 序列化存储

JSON

import (
    "encoding/json"
    "os"
)

type User struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}

// 序列化为JSON并保存
user := User{Name: "Alice", Email: "alice@example.com"}
data, err := json.Marshal(user)
if err != nil {
    panic(err)
}
err = os.WriteFile("user.json", data, 0644)
if err != nil {
    panic(err)
}

// 从JSON读取
fileData, err := os.ReadFile("user.json")
if err != nil {
    panic(err)
}
var loadedUser User
err = json.Unmarshal(fileData, &loadedUser)
if err != nil {
    panic(err)
}
fmt.Println(loadedUser)

Gob (Go二进制序列化)

import (
    "encoding/gob"
    "os"
)

// 写入Gob
file, err := os.Create("user.gob")
if err != nil {
    panic(err)
}
defer file.Close()

encoder := gob.NewEncoder(file)
err = encoder.Encode(user)
if err != nil {
    panic(err)
}

// 读取Gob
file, err = os.Open("user.gob")
if err != nil {
    panic(err)
}
defer file.Close()

decoder := gob.NewDecoder(file)
var decodedUser User
err = decoder.Decode(&decodedUser)
if err != nil {
    panic(err)
}
fmt.Println(decodedUser)

选择建议

  1. 简单键值存储:Redis或BoltDB
  2. 关系型数据:PostgreSQL/MySQL/SQLite
  3. 文档存储:MongoDB
  4. 本地小型应用:SQLite或BoltDB
  5. 需要高性能缓存:Redis

在Linux平台上,Golang与这些存储方案的集成通常都非常顺畅,大多数都有成熟的驱动和良好的性能表现。