Skip to content

Commit c2f256e

Browse files
committed
add tableName
1 parent 82eb2b7 commit c2f256e

File tree

2 files changed

+101
-2
lines changed

2 files changed

+101
-2
lines changed

example/main.go

+92
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"log"
7+
8+
"github.com/nilorg/eventbus"
9+
"github.com/nilorg/outbox"
10+
"github.com/streadway/amqp"
11+
"gorm.io/driver/mysql"
12+
"gorm.io/gorm"
13+
"gorm.io/gorm/schema"
14+
)
15+
16+
var (
17+
db *gorm.DB
18+
bus eventbus.EventBus
19+
engine outbox.Engine
20+
)
21+
22+
func init() {
23+
var (
24+
err error
25+
conn *amqp.Connection
26+
)
27+
conn, err = amqp.Dial("amqp://root:test123@localhost:5672/")
28+
if err != nil {
29+
panic(err)
30+
}
31+
bus, err = eventbus.NewRabbitMQ(conn)
32+
if err != nil {
33+
panic(err)
34+
}
35+
db, err = gorm.Open(
36+
mysql.Open("root:test123@tcp(127.0.0.1:3306)/outbox?charset=utf8&parseTime=True&loc=Local"),
37+
&gorm.Config{
38+
NamingStrategy: schema.NamingStrategy{
39+
SingularTable: true,
40+
},
41+
},
42+
)
43+
if err != nil {
44+
panic(err)
45+
}
46+
engine, err = outbox.New(outbox.EngineTypeGorm, db, bus)
47+
if err != nil {
48+
panic(err)
49+
}
50+
engine.SubscribeAsync(context.Background(), "user.commit", func(ctx context.Context, msg *outbox.Message) error {
51+
fmt.Printf("user.commit: %+v\n", msg)
52+
return nil
53+
})
54+
}
55+
56+
func main() {
57+
db.AutoMigrate(User{})
58+
testUserTran()
59+
}
60+
61+
func testUserTran() {
62+
ctx := context.Background()
63+
var (
64+
tx interface{}
65+
err error
66+
)
67+
tx, err = engine.Begin(ctx)
68+
if err != nil {
69+
log.Printf("tx error: %v", err)
70+
return
71+
}
72+
txDb := tx.(*gorm.DB)
73+
err = txDb.Create(&User{
74+
Name: "test_name",
75+
Age: 11,
76+
}).Error
77+
if err != nil {
78+
engine.Rollback(ctx)
79+
return
80+
}
81+
engine.Commit(ctx, &outbox.CommitMessage{
82+
Topic: "user.commit",
83+
Value: "提交内容。。。",
84+
})
85+
}
86+
87+
// User ...
88+
type User struct {
89+
gorm.Model
90+
Name string
91+
Age int
92+
}

model.go

+9-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,13 @@ package outbox
22

33
import "time"
44

5+
const (
6+
// PublishedTableName ...
7+
PublishedTableName = "outbox_published"
8+
// ReceivedTableName ...
9+
ReceivedTableName = "outbox_received"
10+
)
11+
512
// Published ...
613
type Published struct {
714
ID int64 `json:"id" gorm:"column:id;primaryKey;type:BIGINT(20)"`
@@ -16,7 +23,7 @@ type Published struct {
1623

1724
// TableName ...
1825
func (Published) TableName() string {
19-
return "published"
26+
return PublishedTableName
2027
}
2128

2229
// Received ...
@@ -34,5 +41,5 @@ type Received struct {
3441

3542
// TableName ...
3643
func (Received) TableName() string {
37-
return "received"
44+
return ReceivedTableName
3845
}

0 commit comments

Comments
 (0)