分片

分片插件使用 SQL 解析器和替换将大表拆分为较小的表,将查询重定向到分片表。为您提供高性能的数据库访问。

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

特性

  • 非侵入式设计。加载插件,指定配置,就完成了。
  • 闪电般快速。没有基于网络的中间件,与 Go 一样快。
  • 支持多种数据库。PostgreSQL 已测试,MySQL 和 SQLite 即将推出。
  • 允许您自定义主键生成器(内置密钥生成器、序列、雪花算法...)。

用法

配置分片中间件,注册要分片的表。有关配置详细信息,请参阅 Godoc

import (
"fmt"

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

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

db.Use(sharding.Register(sharding.Config{
ShardingKey: "user_id",
NumberOfShards: 64,
PrimaryKeyGenerator: sharding.PKSnowflake,
}, "orders").Register(sharding.Config{
ShardingKey: "user_id",
NumberOfShards: 256,
PrimaryKeyGenerator: sharding.PKSnowflake,
// This case for show up give notifications, audit_logs table use same sharding rule.
}, Notification{}, AuditLog{}))

像往常一样使用数据库会话。请注意,在操作分片表时,查询应具有“分片键”。

// Gorm create example, this will insert to orders_02
db.Create(&Order{UserID: 2})
// sql: INSERT INTO orders_2 ...

// Show have use Raw SQL to insert, this will insert into orders_03
db.Exec("INSERT INTO orders(user_id) VALUES(?)", int64(3))

// This will throw ErrMissingShardingKey error, because there not have sharding key presented.
db.Create(&Order{Amount: 10, ProductID: 100})
fmt.Println(err)

// Find, this will redirect query to orders_02
var orders []Order
db.Model(&Order{}).Where("user_id", int64(2)).Find(&orders)
fmt.Printf("%#v\n", orders)

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

// This will throw ErrMissingShardingKey error, because WHERE conditions not included sharding key
err = db.Model(&Order{}).Where("product_id", "1").Find(&orders).Error
fmt.Println(err)

// Update and Delete are similar to create and query
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) // ErrMissingShardingKey

完整的示例 在此处

铂金赞助商

黄金赞助商

铂金赞助商

黄金赞助商