1、零值字段也更新

1
2
3
4
5
6
7
8
9
10
// gorm特性,当用struct更新时,里面的零值是不会被更新的,需要转换为map,这样零值也可被更新
hostsMap := structs.Map(&hosts)
// 更新集群相关信息,忽略对id字段的更新
dbUpdate := tx.Model(&hosts).Where("ip = ?", hosts.Ip).Omit("id").Updates(hostsMap)
if err = dbUpdate.Error; err != nil {
return err
}
if dbUpdate.RowsAffected == 0 {
return errors.New(fmt.Sprintf("Node ip [%s] was not exists.", ip))
}

2、事务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// 开启事务
err = util.MysqlConnetion.Transaction(func(tx *gorm.DB) error {
if err = tx.Create(&hosts).Error; err != nil {
return err
}
if len(clusterList) > 0 && isBatch {
if err = tx.Exec(buffer.String()).Error; err != nil {
return err
}
}
// 重新创建kubelet的Endpoint
flagOperator := gjson.Get(util.GetConfig(), "monitor.enableOperator").Bool()
if flagOperator {
// 确认要添加的节点是否为k8s节点,如果是,则更新kubelet的Endpoint
if _, ok := nodeIp[ip]; ok {
addresses := []v1.EndpointAddress{}
for ip = range nodeIp {
addr := v1.EndpointAddress{}
addr.IP = ip
addresses = append(addresses, addr)
}
kubeletEpName := "kubelet"
re, err := serviceDiscovery.CreateKubernetesEndpoints("monitoring", kubeletEpName, "kubernetes-kubelet", 10250, "https-metrics", v1.ProtocolTCP, addresses, true)
if !re {
if err != nil {
util.Logger.Error(fmt.Sprintf("create Endpoints error is %v", err.Error()))
} else {
util.Logger.Infof(fmt.Sprintf("Endpoints %v 已存在,退出", kubeletEpName))
}
}
}
}
return nil
})
return err

https://gorm.io/zh_CN/docs/advanced_query.html