MYSQL分布式事物案例

func tx() {
    tx := settle.Orm()
    trans := settle.OrderTrans{}
    // 启动协调器
    settle.OrderTransandler.Insert(nil, &trans)
    // orderDb
    orderDb := model.Orm()
    orderDb.Exec("XA START '" + cast.ToString(trans.Id) + "';")
    err := orderDb.Exec("update order_table set create_time = 1 where id = ?", 1).Error
    if err != nil {
        fmt.Printf("%#v\n", err.Error())
    }
    orderDb.Exec("XA END '" + cast.ToString(trans.Id) + "';")
    orderDb.Exec("XA PREPARE '" + cast.ToString(trans.Id) + "';")
    err = tx.Exec("update order_trans set tx1 = 1 where id = ?", trans.Id).Error
    if err != nil {
        fmt.Printf("%#v\n", err.Error())
    }
    // misunDb
    misunDb := misun.Orm()
    misunDb.Exec("XA START '" + cast.ToString(trans.Id) + "';")
    err = misunDb.Exec("update order_table set create_time = 1 where id = ?", 1).Error
    if err != nil {
        fmt.Printf("%#v\n", err.Error())
    }
    misunDb.Exec("XA END '" + cast.ToString(trans.Id) + "';")
    misunDb.Exec("XA PREPARE '" + cast.ToString(trans.Id) + "';")
    err = tx.Exec("update order_trans set tx2 = 1 where id = ?", trans.Id).Error
    if err != nil {
        fmt.Printf("%#v\n", err.Error())
    }
    time.Sleep(3 * time.Minute)
    // commit
    misunDb.Exec("XA COMMIT '" + cast.ToString(trans.Id) + "';")
    err = tx.Exec("update order_trans set tx1 = 2 where id = ?", trans.Id).Error
    if err != nil {
        fmt.Printf("%#v\n", err.Error())
    }
    orderDb.Exec("XA COMMIT '" + cast.ToString(trans.Id) + "';")
    err = tx.Exec("update order_trans set tx2 = 2 where id = ?", trans.Id).Error
    if err != nil {
        fmt.Printf("%#v\n", err.Error())
    }

}

func txCron() {
    orderDb := model.Orm()
    misunDb := misun.Orm()
    list, _ := settle.OrderTransHandler.GetList("tx1 < 1 or tx2 < 1")
    for k1 := range list {
        misunDb.Exec("XA ROLLBACK '" + cast.ToString(list[k1].Id) + "';")
        orderDb.Exec("XA ROLLBACK '" + cast.ToString(list[k1].Id) + "';")
    }
    list, _ = settle.OrderTransHandler.GetList("tx1 < 2 or tx2 < 2")
    for k1 := range list {
        if list[k1].Tx1 != 2 {
            misunDb.Exec("XA COMMIT '" + cast.ToString(list[k1].Id) + "';")
        }
        if list[k1].Tx2 != 2 {
            orderDb.Exec("XA COMMIT '" + cast.ToString(list[k1].Id) + "';")
        }

    }
}

你可能感兴趣的:(MYSQL分布式事物案例)