Browse Source

mongo example updated

pull/273/head
yedf2 4 years ago
parent
commit
7c7c2485c3
  1. 2
      sqls/busi.mongo.js
  2. 16
      test/busi/busi.go
  3. 6
      test/busi/utils.go

2
sqls/busi.mongo.js

@ -3,4 +3,4 @@ db.user_account.drop()
db.user_account.createIndex({ user_id: NumberLong(1) }, { unique: true })
db.user_account.insert({ user_id: NumberLong(1), balance: 10000 })
db.user_account.insert({ user_id: NumberLong(2), balance: 10000 })
db.user_account.insert({ user_id: NumberLong(2), balance: 10000 })

16
test/busi/busi.go

@ -88,7 +88,21 @@ func SagaMongoAdjustBalance(ctx context.Context, mc *mongo.Client, uid int, amou
bson.D{{Key: "user_id", Value: uid}},
bson.D{{Key: "$inc", Value: bson.D{{Key: "balance", Value: amount}}}})
logger.Debugf("dtm_busi.user_account $inc balance of %d by %d err: %v", uid, amount, err)
return err
if err != nil {
return err
}
var res bson.M
err = mc.Database("dtm_busi").Collection("user_account").FindOne(ctx,
bson.D{{Key: "user_id", Value: uid}}).Decode(&res)
if err != nil {
return err
}
balance := res["balance"].(float64)
if balance < 0 {
return fmt.Errorf("balance not enough %w", dtmcli.ErrFailure)
}
return nil
}
func tccAdjustTrading(db dtmcli.DB, uid int, amount int) error {

6
test/busi/utils.go

@ -145,7 +145,7 @@ var (
// MongoGet get mongo client
func MongoGet() *mongo.Client {
mongoOnce.Do(func() {
uri := fmt.Sprintf("mongodb://%s:27017/?retryWrites=false", StoreHost)
uri := fmt.Sprintf("mongodb://%s:27017/?retryWrites=false&directConnection=true", StoreHost)
ctx := context.Background()
logger.Infof("connecting to mongo: %s", uri)
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
@ -169,9 +169,9 @@ func SetRedisBothAccount(amountA int, ammountB int) {
func SetMongoBothAccount(amountA int, amountB int) {
mc := MongoGet()
col := mc.Database("dtm_busi").Collection("user_account")
_, err := col.ReplaceOne(context.Background(), bson.D{{Key: "user_id", Value: TransOutUID}}, bson.D{{Key: "user_id", Value: TransOutUID}, {Key: "balance", Value: amountA}}, options.Replace().SetUpsert(true))
_, err := col.ReplaceOne(context.Background(), bson.D{{Key: "user_id", Value: TransOutUID}}, bson.D{{Key: "user_id", Value: TransOutUID}, {Key: "balance", Value: float64(amountA)}}, options.Replace().SetUpsert(true))
dtmimp.E2P(err)
_, err = col.ReplaceOne(context.Background(), bson.D{{Key: "user_id", Value: TransInUID}}, bson.D{{Key: "user_id", Value: TransInUID}, {Key: "balance", Value: amountB}}, options.Replace().SetUpsert(true))
_, err = col.ReplaceOne(context.Background(), bson.D{{Key: "user_id", Value: TransInUID}}, bson.D{{Key: "user_id", Value: TransInUID}, {Key: "balance", Value: float64(amountB)}}, options.Replace().SetUpsert(true))
dtmimp.E2P(err)
}

Loading…
Cancel
Save