在Linux平台上使用Golang进行数据存储有多种选择,以下是主要的几种方案及其实现方法:
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()
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)
}
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)
}
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)
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数据库类似
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)
}
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)
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)
在Linux平台上,Golang与这些存储方案的集成通常都非常顺畅,大多数都有成熟的驱动和良好的性能表现。