1,地址:
GitHub - liuhongdi/digv16: gin框架中通过gorm使用事务
2,功能:以下订单为例,演示了在gorm中启用事务
3, 项目结构:如图:
说明:刘宏缔的go森林是一个专注golang的博客,
网站:https://blog.imgtouch.com
原文: go语言web开发系列之十六:gin框架中通过gorm使用事务 – 架构森林
说明:作者:刘宏缔 邮箱: [email protected]
1,数据表:
2,建表sql:
CREATE TABLE `m_goods` (
`goodsId` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '商品id',
`goodsName` varchar(200) NOT NULL DEFAULT '' COMMENT '商品名称',
`stock` int unsigned NOT NULL DEFAULT '0' COMMENT '库存数量',
PRIMARY KEY (`goodsId`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='商品表'
CREATE TABLE `m_order` (
`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 '订单金额',
PRIMARY KEY (`orderId`),
KEY `userId` (`userId`)
) 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 '购买数量',
PRIMARY KEY (`ogId`),
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
(1, '施丹兰蜂蜜牛奶手工皂', 10);
1,controller/orderController.go
package controller
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/liuhongdi/digv16/global"
"github.com/liuhongdi/digv16/service"
)
type OrderController struct{}
//result:= global.NewResult(c)
func NewOrderController() OrderController {
return OrderController{}
}
//新加一个订单
func (o *OrderController) AddOne(c *gin.Context) {
result := global.NewResult(c)
goodsId:=1;
buyNum:=11;
orderOne,err := service.AddOneOrder(int64(goodsId),buyNum);
if err != nil {
result.Error(404,"数据处理错误")
} else {
result.Success(&orderOne);
}
return
}
//新加一个订单,使用tx
func (o *OrderController) AddOneTx(c *gin.Context) {
result := global.NewResult(c)
goodsId:=1;
buyNum:=11;
orderOne,err := service.AddOneOrderTx(int64(goodsId),buyNum);
fmt.Println("orderOne:");
fmt.Println(orderOne);
fmt.Println(":end:");
//if ()
if (orderOne == nil || err != nil) {
result.Error(20001,"数据处理错误")
} else {
result.Success(&orderOne);
}
return
}
2,service/order.go
package service
import (
"github.com/liuhongdi/digv16/dao"
"github.com/liuhongdi/digv16/model"
)
//新加一个订单
func AddOneOrder(goodsId int64,buyNum int) (*model.Order, error) {
return dao.AddOneOrder(goodsId,buyNum)
}
//新加一个订单,使用tx
func AddOneOrderTx(goodsId int64,buyNum int) (*model.Order, error) {
return dao.AddOneOrderTx(goodsId,buyNum)
}
3,dao/order.go
package dao
import (
"errors"
"fmt"
"github.com/liuhongdi/digv16/global"
"github.com/liuhongdi/digv16/model"
"gorm.io/gorm"
)
//添加一个订单
func AddOneOrder(goodsId int64,buyNum int) (*model.Order, error) {
//添加order
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) {
return nil,result.Error
}
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
}
//return
return &order,nil
}
//添加一个订单
func AddOneOrderTx(goodsId int64,buyNum int) (*model.Order, error) {
// 事务开始后,需要使用 tx 处理数据
tx := global.DBLink.Begin()
defer func() {
if r := recover(); r != nil {
fmt.Println("this is in defer recover")
tx.Rollback()
}
}()
if err := tx.Error; err != nil {
return nil,err
}
//添加order
order := model.Order{UserId: 1, SalePrice: "20.00"}
resultCO := tx.Debug().Create(&order) // 通过数据的指针来创建
if (resultCO.Error != nil) {
tx.Rollback()
return nil,resultCO.Error
}
/*
var z int = 0
var i int = 100 / z
fmt.Println("i:%i",i)
*/
//减库存
result := tx.Debug().Table("m_goods").Where("goodsId = ? and stock >= ?", goodsId,buyNum).Update("stock", gorm.Expr("stock - ?", buyNum))
if (result.Error != nil) {
tx.Rollback()
return nil,result.Error
}
if (result.RowsAffected <= 0){
tx.Rollback()
fmt.Println("减库存失败")
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) {
tx.Rollback()
return nil,resultCOG.Error
}
//commit
fmt.Println("begin commit")
errCM := tx.Commit().Error
if (errCM != nil) {
fmt.Println("begin return1")
tx.Rollback()
return nil,errCM
}else {
fmt.Println("begin return2")
return &order,nil
}
}
4,model/goods.go
package model
type Goods struct {
GoodsId int64 `gorm:"column:goodsId",json:"goodsId"` // 自增
GoodsName string `gorm:"column:goodsName",json:"goodsName"` // 用户id
Stock int `gorm:"column:stock",json:"stock"` // 售价
}
func (Goods) TableName() string {
return "m_goods"
}
5,model/order.go
package model
type Order struct {
OrderId int64 `gorm:"primaryKey;autoIncrement;column:orderId",json:"orderid"` // 自增
UserId int64 `gorm:"column:userId",json:"userid"` // 用户id
SalePrice string `gorm:"column:salePrice",json:"saleprice"` // 售价
}
func (Order) TableName() string {
return "m_order"
}
6,router/router.go
package router
import (
"github.com/gin-gonic/gin"
"github.com/liuhongdi/digv16/controller"
"github.com/liuhongdi/digv16/global"
"log"
"runtime/debug"
)
func Router() *gin.Engine {
router := gin.Default()
//处理异常
router.NoRoute(HandleNotFound)
router.NoMethod(HandleNotFound)
router.Use(Recover)
// 路径映射
goodsc:=controller.NewGoodsController()
router.GET("/goods/getone/:id", goodsc.GetOne);
//router.GET("/article/list", articlec.GetList);
orderc:=controller.NewOrderController()
router.GET("/order/addone", orderc.AddOne);
router.GET("/order/addonetx", orderc.AddOneTx);
return router
}
func HandleNotFound(c *gin.Context) {
global.NewResult(c).Error(404,"资源未找到")
return
}
func Recover(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
//打印错误堆栈信息
log.Printf("panic: %v\n", r)
debug.PrintStack()
global.NewResult(c).Error(500,"服务器内部错误")
}
}()
//加载完 defer recover,继续后续接口调用
c.Next()
}
7,其他相关代码可访问github查看
1,测试除0错:
访问:
http://127.0.0.1:8080/order/addonetx
返回:
2,测试扣减库存出错
把dao/order.go中,
AddOneOrderTx方法中的除0错代码注释掉
/*
var z int = 0
var i int = 100 / z
fmt.Println("i:%i",i)
*/
再次执行:访问:
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
go 1.15
require (
github.com/gin-gonic/gin v1.6.3
github.com/jinzhu/gorm v1.9.16 // indirect
gorm.io/driver/mysql v1.0.1
gorm.io/gorm v1.20.6
)