阶段2(上):后端专题 Go/Gin/PostgreSQL/MySQL/Redis/MQ/gRPC 的课程、企业场景、面试题和可运行示例
This commit is contained in:
1 parent
0bae9916a9
commit
5eb67c5d08
65 files changed
+6457
-77
No files matched your search
@@ -0,0 +1,13 @@
|
||||
module example/orderstate
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require github.com/jackc/pgx/v5 v5.11.0
|
||||
|
||||
require (
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
golang.org/x/sync v0.17.0 // indirect
|
||||
golang.org/x/text v0.29.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,26 @@
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
|
||||
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,97 @@
|
||||
// Package orderstate 订单状态机:合法流转校验 + 乐观锁 + 审计日志(与状态修改在同一个事务里提交)。
|
||||
package orderstate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
const Schema = `
|
||||
CREATE TABLE IF NOT EXISTS orders (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
version INT NOT NULL DEFAULT 1,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS order_events (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
order_id BIGINT NOT NULL REFERENCES orders(id),
|
||||
from_status TEXT NOT NULL,
|
||||
to_status TEXT NOT NULL,
|
||||
actor TEXT NOT NULL,
|
||||
reason TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);`
|
||||
|
||||
// 允许的状态流转:只有这里列出的才合法
|
||||
var transitions = map[string][]string{
|
||||
"pending": {"paid", "cancelled"},
|
||||
"paid": {"shipped", "refunding"},
|
||||
"shipped": {"completed"},
|
||||
"refunding": {"refunded", "paid"},
|
||||
}
|
||||
|
||||
var (
|
||||
ErrIllegal = errors.New("不允许的状态流转")
|
||||
ErrConflict = errors.New("订单已被其他操作修改,请刷新后重试")
|
||||
ErrNotFound = errors.New("订单不存在")
|
||||
)
|
||||
|
||||
func allowed(from, to string) bool {
|
||||
for _, s := range transitions[from] {
|
||||
if s == to {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type Order struct {
|
||||
ID int64
|
||||
Status string
|
||||
Version int
|
||||
}
|
||||
|
||||
func Get(ctx context.Context, db *pgxpool.Pool, id int64) (Order, error) {
|
||||
var o Order
|
||||
err := db.QueryRow(ctx, `SELECT id, status, version FROM orders WHERE id = $1`, id).Scan(&o.ID, &o.Status, &o.Version)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return o, ErrNotFound
|
||||
}
|
||||
return o, err
|
||||
}
|
||||
|
||||
// Transition 把订单从 cur 状态改成 to。cur 是调用方读到的版本(乐观锁)。
|
||||
func Transition(ctx context.Context, db *pgxpool.Pool, cur Order, to, actor, reason string) (Order, error) {
|
||||
if !allowed(cur.Status, to) {
|
||||
return cur, fmt.Errorf("%s -> %s: %w", cur.Status, to, ErrIllegal)
|
||||
}
|
||||
tx, err := db.Begin(ctx)
|
||||
if err != nil {
|
||||
return cur, err
|
||||
}
|
||||
defer tx.Rollback(ctx) // 提交成功后再回滚是无害的
|
||||
|
||||
tag, err := tx.Exec(ctx,
|
||||
`UPDATE orders SET status = $1, version = version + 1, updated_at = now()
|
||||
WHERE id = $2 AND status = $3 AND version = $4`, to, cur.ID, cur.Status, cur.Version)
|
||||
if err != nil {
|
||||
return cur, err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return cur, ErrConflict
|
||||
}
|
||||
if _, err := tx.Exec(ctx,
|
||||
`INSERT INTO order_events (order_id, from_status, to_status, actor, reason) VALUES ($1, $2, $3, $4, $5)`,
|
||||
cur.ID, cur.Status, to, actor, reason); err != nil {
|
||||
return cur, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return cur, err
|
||||
}
|
||||
return Order{ID: cur.ID, Status: to, Version: cur.Version + 1}, nil
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package orderstate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// 需要 PostgreSQL:TEST_DATABASE_URL=postgres://user:pass@localhost:5432/db?sslmode=disable go test ./...
|
||||
func setup(t *testing.T) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
url := os.Getenv("TEST_DATABASE_URL")
|
||||
if url == "" {
|
||||
t.Skip("未设置 TEST_DATABASE_URL,跳过集成测试")
|
||||
}
|
||||
ctx := context.Background()
|
||||
schema := fmt.Sprintf("t_order_%d", time.Now().UnixNano())
|
||||
admin, err := pgxpool.New(ctx, url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := admin.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, _ := pgxpool.ParseConfig(url)
|
||||
cfg.ConnConfig.RuntimeParams["search_path"] = schema // 每次测试用独立的 schema
|
||||
db, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
db.Close()
|
||||
_, _ = admin.Exec(ctx, "DROP SCHEMA "+schema+" CASCADE")
|
||||
admin.Close()
|
||||
})
|
||||
if _, err := db.Exec(ctx, Schema); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func newOrder(t *testing.T, db *pgxpool.Pool) Order {
|
||||
t.Helper()
|
||||
var id int64
|
||||
if err := db.QueryRow(context.Background(), "INSERT INTO orders DEFAULT VALUES RETURNING id").Scan(&id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
o, err := Get(context.Background(), db, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func TestAllowed(t *testing.T) {
|
||||
if !allowed("pending", "paid") || allowed("pending", "shipped") || allowed("completed", "paid") {
|
||||
t.Fatal("状态流转表不对")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransitionAndAudit(t *testing.T) {
|
||||
db := setup(t)
|
||||
ctx := context.Background()
|
||||
o := newOrder(t, db)
|
||||
o, err := Transition(ctx, db, o, "paid", "payment-callback", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Transition(ctx, db, o, "completed", "admin", ""); !errors.Is(err, ErrIllegal) {
|
||||
t.Fatalf("paid -> completed 应该不允许,得到 %v", err)
|
||||
}
|
||||
var n int
|
||||
_ = db.QueryRow(ctx, "SELECT count(*) FROM order_events WHERE order_id = $1", o.ID).Scan(&n)
|
||||
if n != 1 {
|
||||
t.Fatalf("审计日志条数 = %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentCancelAndPay(t *testing.T) {
|
||||
db := setup(t)
|
||||
ctx := context.Background()
|
||||
o := newOrder(t, db) // 两个操作读到的是同一个版本
|
||||
var wg sync.WaitGroup
|
||||
errs := make([]error, 2)
|
||||
for i, to := range []string{"paid", "cancelled"} {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, errs[i] = Transition(ctx, db, o, to, "test", "")
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
ok, conflict := 0, 0
|
||||
for _, err := range errs {
|
||||
switch {
|
||||
case err == nil:
|
||||
ok++
|
||||
case errors.Is(err, ErrConflict):
|
||||
conflict++
|
||||
default:
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if ok != 1 || conflict != 1 {
|
||||
t.Fatalf("应该一个成功一个冲突,得到 ok=%d conflict=%d", ok, conflict)
|
||||
}
|
||||
cur, _ := Get(ctx, db, o.ID)
|
||||
var n int
|
||||
_ = db.QueryRow(ctx, "SELECT count(*) FROM order_events WHERE order_id = $1", o.ID).Scan(&n)
|
||||
if cur.Version != 2 || n != 1 {
|
||||
t.Fatalf("版本 %d,审计 %d 条", cur.Version, n)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user