createservicelogic.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // udeServer: CreateService 走事务 —— 同一事务内插 t_service + N 条 t_directory,
  2. // 任意一条 INSERT 失败,全部回滚,不留脏数据。
  3. package logic
  4. import (
  5. "context"
  6. "fmt"
  7. "strings"
  8. "udeServer/internal/model"
  9. "udeServer/internal/svc"
  10. "udeServer/internal/types"
  11. "github.com/zeromicro/go-zero/core/logx"
  12. "github.com/zeromicro/go-zero/core/stores/sqlx"
  13. )
  14. type CreateServiceLogic struct {
  15. logx.Logger
  16. ctx context.Context
  17. svcCtx *svc.ServiceContext
  18. }
  19. func NewCreateServiceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateServiceLogic {
  20. return &CreateServiceLogic{
  21. Logger: logx.WithContext(ctx),
  22. ctx: ctx,
  23. svcCtx: svcCtx,
  24. }
  25. }
  26. func (l *CreateServiceLogic) CreateService(req *types.CreateServiceReq) (*types.ServiceResp, error) {
  27. var svcId int64
  28. err := l.svcCtx.DB.Transact(func(session sqlx.Session) error {
  29. // 把 model 绑到事务 session 上,后续所有写操作都走同一个连接/事务
  30. svcModel := l.svcCtx.ServiceModel.WithSession(session)
  31. dirModel := l.svcCtx.DirectoryModel.WithSession(session)
  32. // 1. 插服务
  33. svcData := &model.TService{
  34. Name: nullString(req.Name),
  35. Ip: nullString(req.Ip),
  36. Port: nullString(req.Port),
  37. Iden: nullString(req.Iden),
  38. KeyIden: nullString(req.KeyIden),
  39. KeyAlgo: nullString(req.KeyAlgo),
  40. Status: nullString(req.Status),
  41. }
  42. svcRes, err := svcModel.Insert(l.ctx, svcData)
  43. if err != nil {
  44. return fmt.Errorf("insert t_service: %w", err)
  45. }
  46. svcId, err = svcRes.LastInsertId()
  47. if err != nil {
  48. return fmt.Errorf("get last insert id: %w", err)
  49. }
  50. // 2. 插保护目录(与上面的服务同事务,任一条失败整体回滚)
  51. for _, dir := range req.Directories {
  52. path := strings.TrimSpace(dir)
  53. if path == "" {
  54. continue
  55. }
  56. _, err := dirModel.Insert(l.ctx, &model.TDirectory{
  57. ServiceId: nullInt64(svcId),
  58. Directory: nullString(path),
  59. })
  60. if err != nil {
  61. return fmt.Errorf("insert t_directory[%s]: %w", path, err)
  62. }
  63. }
  64. return nil
  65. })
  66. if err != nil {
  67. l.Errorf("create service tx failed: %v", err)
  68. return nil, err
  69. }
  70. // 事务提交后再回查完整实体(CreateAt 由 DB 默认值生成)
  71. created, err := findService(l.ctx, l.svcCtx.ServiceModel, svcId)
  72. if err != nil {
  73. return nil, err
  74. }
  75. return toServiceResp(created), nil
  76. }