一,演示项目的相关信息
1,地址:
https://github.com/liuhongdi/digv16
2,功能:以下订单为例,演示了在gorm中启用事务
3, 项目结构:如图:
说明:刘宏缔的go森林是一个专注golang的博客, 地址:https://blog.csdn.net/weixin_43881017
说明:作者:刘宏缔 邮箱: [email protected]
二,数据库及sql
1,数据表:
2,建表sql:
-
-
`goodsId` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '商品id',
-
`goodsName` varchar(200) NOT NULL DEFAULT '' COMMENT '商品名称',
-
`stock` int unsigned NOT NULL DEFAULT '0' COMMENT '库存数量',
-
-
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='商品表'
-
-
`orderId` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '订单id',
-
`userId` bigint unsigned NOT NULL DEFAULT '0' COMMENT '用户id',
-
`salePrice` decimal(10,0) NOT NULL DEFAULT '0' COMMENT '订单金额',
-
-
-
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='订单表'
-
CREATE TABLE `m_order_goods` (
-
`ogId` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
-
`orderId` bigint unsigned NOT NULL COMMENT '订单id',
-
`goodsId` bigint unsigned NOT NULL COMMENT '商品id',
-
`buyNum` int unsigned NOT NULL COMMENT '购买数量',
-
-
UNIQUE KEY `orderId_2` (`orderId`,`goodsId`)
-
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='订单商品表'
3,插入一条演示数据:
-
INSERT INTO `m_goods` (`goodsId`, `goodsName`, `stock`) VALUES
-
三,go代码说明
1,controller/orderController.go
-
-
-
-
-
"github.com/gin-gonic/gin"
-
"github.com/liuhongdi/digv16/global"
-
"github.com/liuhongdi/digv16/service"
-
-
-
type OrderController struct{}
-
-
-
-
func NewOrderController() OrderController {
-
-
-
-
-
func (o *OrderController) AddOne(c *gin.Context) {
-
result := global.NewResult(c)
-
-
-
-
-
orderOne,err := service.AddOneOrder(int64(goodsId),buyNum);
-
-
result.Error(404,"数据处理错误")
-
-
result.Success(&orderOne);
-
-
-
-
-
-
-
func (o *OrderController) AddOneTx(c *gin.Context) {
-
result := global.NewResult(c)
-
-
-
-
orderOne,err := service.AddOneOrderTx(int64(goodsId),buyNum);
-
-
fmt.Println("orderOne:");
-
-
-
-
if (orderOne == nil || err != nil) {
-
result.Error(20001,"数据处理错误")
-
-
result.Success(&orderOne);
-
-
-
2,service/order.go
-
-
-
-
"github.com/liuhongdi/digv16/dao"
-
"github.com/liuhongdi/digv16/model"
-
-
-
-
func AddOneOrder(goodsId int64,buyNum int) (*model.Order, error) {
-
return dao.AddOneOrder(goodsId,buyNum)
-
-
-
-
func AddOneOrderTx(goodsId int64,buyNum int) (*model.Order, error) {
-
return dao.AddOneOrderTx(goodsId,buyNum)
-
3,dao/order.go
-
-
-
-
-
-
"github.com/liuhongdi/digv16/global"
-
"github.com/liuhongdi/digv16/model"
-
-
-
-
-
func AddOneOrder(goodsId int64,buyNum int) (*model.Order, error) {
-
-
order := model.Order{UserId: 1, SalePrice: "20.00"}
-
resultCO := global.DBLink.Create(&order)
-
if (resultCO.Error != nil) {
-
return nil,resultCO.Error
-
-
-
result := global.DBLink.Debug().Table("m_goods").Where("goodsId = ? and stock >= ?", goodsId,buyNum).Update("stock", gorm.Expr("stock - ?", buyNum))
-
if (result.Error != nil) {
-
-
-
if (result.RowsAffected <= 0){
-
return nil,errors.New("减库存失败")
-
-
-
orderId := order.OrderId;
-
orderGoods := model.OrderGoods{OrderId:orderId,GoodsId:goodsId,BuyNum:buyNum}
-
resultCOG := global.DBLink.Create(&orderGoods)
-
if (resultCOG.Error != nil) {
-
return nil,resultCOG.Error
-
-
-
-
-
-
-
-
func AddOneOrderTx(goodsId int64,buyNum int) (*model.Order, error) {
-
-
tx := global.DBLink.Begin()
-
-
-
if r := recover(); r != nil {
-
fmt.Println("this is in defer recover")
-
-
-
-
-
if err := tx.Error; err != nil {
-
-
-
-
-
order := model.Order{UserId: 1, SalePrice: "20.00"}
-
resultCO := tx.Debug().Create(&order)
-
if (resultCO.Error != nil) {
-
-
return nil,resultCO.Error
-
-
-
-
-
-
-
-
-
result := tx.Debug().Table("m_goods").Where("goodsId = ? and stock >= ?", goodsId,buyNum).Update("stock", gorm.Expr("stock - ?", buyNum))
-
if (result.Error != nil) {
-
-
-
-
if (result.RowsAffected <= 0){
-
-
-
return nil,errors.New("减库存失败")
-
-
-
orderId := order.OrderId;
-
orderGoods := model.OrderGoods{OrderId:orderId,GoodsId:goodsId,BuyNum:buyNum}
-
resultCOG := tx.Debug().Create(&orderGoods)
-
if (resultCOG.Error != nil) {
-
-
return nil,resultCOG.Error
-
-
-
fmt.Println("begin commit")
-
errCM := tx.Commit().Error
-
-
fmt.Println("begin return1")
-
-
-
-
fmt.Println("begin return2")
-
-
-
4,model/goods.go
-
-
-
-
GoodsId int64 `gorm:"column:goodsId",json:"goodsId"`
-
GoodsName string `gorm:"column:goodsName",json:"goodsName"`
-
Stock int `gorm:"column:stock",json:"stock"`
-
-
-
func (Goods) TableName() string {
-
-
5,model/order.go
-
-
-
-
OrderId int64 `gorm:"primaryKey;autoIncrement;column:orderId",json:"orderid"`
-
UserId int64 `gorm:"column:userId",json:"userid"`
-
SalePrice string `gorm:"column:salePrice",json:"saleprice"`
-
-
-
func (Order) TableName() string {
-
-
6,router/router.go
-
-
-
-
"github.com/gin-gonic/gin"
-
"github.com/liuhongdi/digv16/controller"
-
"github.com/liuhongdi/digv16/global"
-
-
-
-
-
func Router() *gin.Engine {
-
-
-
router.NoRoute(HandleNotFound)
-
router.NoMethod(HandleNotFound)
-
-
-
-
goodsc:=controller.NewGoodsController()
-
router.GET("/goods/getone/:id", goodsc.GetOne);
-
-
-
orderc:=controller.NewOrderController()
-
router.GET("/order/addone", orderc.AddOne);
-
router.GET("/order/addonetx", orderc.AddOneTx);
-
-
-
-
-
func HandleNotFound(c *gin.Context) {
-
global.NewResult(c).Error(404,"资源未找到")
-
-
-
-
func Recover(c *gin.Context) {
-
-
if r := recover(); r != nil {
-
-
log.Printf("panic: %v\n", r)
-
-
global.NewResult(c).Error(500,"服务器内部错误")
-
-
-
-
-
7,其他相关代码可访问github查看
四,测试效果
1,测试除0错:
访问:
http://127.0.0.1:8080/order/addonetx
返回:
2,测试扣减库存出错
把dao/order.go中,
AddOneOrderTx方法中的除0错代码注释掉
-
-
-
-
-
再次执行:访问:
http://127.0.0.1:8080/order/addonetx
可以从控制台看到输出的提示:
-
2021/01/13 13:32:25 /data/liuhongdi/digv16/dao/order.go:69
-
[2.219ms] [rows:0] UPDATE `m_goods` SET `stock`=stock - 11 WHERE goodsId = 1 and stock >= 11
-
3,测试正常执行事务成功
把controller/orderController.go中,
AddOneTx方法,把buyNum的值改为9
buyNum:=9
再次执行:
http://127.0.0.1:8080/order/addonetx
返回:
事务执行已成功
五,使用的库的版本:
-
module github.com/liuhongdi/digv16
-
-
-
-
-
github.com/gin-gonic/gin v1.6.3
-
github.com/jinzhu/gorm v1.9.16 // indirect
-
gorm.io/driver/mysql v1.0.1
-
-
|
请发表评论