InfoSphere/GORM 中文版/ 返回书籍
Advanced Topics

Sharding

qianmoQqianmoQ· 更新于 2026-09-15· 阅读 5 分钟· 0 次阅读

登录后可跨设备保存划线和私人笔记登录

Sharding plugin using SQL parser and replace for splits large tables into smaller ones, redirects Query into sharding tables. Give you a high performance database access.

https://github.com/go-gorm/sharding

Features

  • Non-intrusive design. Load the plugin, specify the config, and all done.
  • Lighting-fast. No network based middlewares, as fast as Go.
  • Multiple database (PostgreSQL, MySQL) support.
  • Integrated primary key generator (Snowflake, PostgreSQL Sequence, Custom, …).

Usage

Config the sharding middleware, register the tables which you want to shard. See Godoc for config details.

import (
    "fmt"

    "gorm.io/driver/postgres"
    "gorm.io/gorm"
    "gorm.io/sharding"
)

db, err := gorm.Open(postgres.New(postgres.Config{DSN: "postgres://localhost:5432/sharding-db?sslmode=disable"))

db.Use(sharding.Register(sharding.Config{
    ShardingKey:         "user_id",
    NumberOfShards:      64,
    PrimaryKeyGenerator: sharding.PKSnowflake,
}, "orders", Notification{}, AuditLog{}))

Use the db session as usual. Just note that the query should have the Sharding Key when operate sharding tables.


db.Create(&Order{UserID: 2})



db.Exec("INSERT INTO orders(user_id) VALUES(?)", int64(3))


db.Create(&Order{Amount: 10, ProductID: 100})
fmt.Println(err)


var orders []Order
db.Model(&Order{}).Where("user_id", int64(2)).Find(&orders)
fmt.Printf("%#v\n", orders)


db.Raw("SELECT * FROM orders WHERE user_id = ?", int64(3)).Scan(&orders)
fmt.Printf("%#v\n", orders)


err = db.Model(&Order{}).Where("product_id", "1").Find(&orders).Error
fmt.Println(err)


db.Exec("UPDATE orders SET product_id = ? WHERE user_id = ?", 2, int64(3))
err = db.Exec("DELETE FROM orders WHERE product_id = 3").Error
fmt.Println(err) 

The full example is here.

GitHub tag (latest SemVer)

评论

登录后参与评论

正在加载评论…