1. 概论
-
Gorm
Gorm 是一个已经迭代了10年+的功能强大的 ORM框架,在字节内部被广泛使用并且拥有非常丰富的开源扩展。
-
Kitex
Kitex 是字节内部 Golang 微服务 RPC 框架,具有高性能、强可扩展的主要特点,支持多协议并且拥有丰富的开源扩展。
-
Hertz
Hertz 是字节内部的 HTTP框架,参考了其他开源框架的优势,结合字节跳动内部的需求,具有高易用性、高性能、高扩展性特点
2. Gorm
//定义 gorm model
type Product struct {
Price uint Code string
}
为 model 定义表名
func (p Product) TableName() string {
return "product";
}
func main(){
db,err := gorm.0pen(
连接数据库
mysgl.0pen(dsn:"user:passtcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local").&gorm.Config{})
if err != nil {
panic( v:"failed to connect database")
}
// Create 创建数据
db.Create(&Product{Code:"D42",Price: 100})
// Read 查询数据
var product Product
db.First(&product, 1) // 根据整形主键查找
db.First(&product,"code = ?", "D42")// 查找 code 字段值为 D42 的记录
// Update - 将 product 的 price 更新为 200 更新数据
db.Model(&product).Update("Price", 200)// Update - 更新多个字段
db.Model(&product).Updates(Product{Price: 200,Code:"F42"})// 使用结构体 仅更新非零值字段
db.Model(&product).Updates(map[stringlinterface{}{"Price": 200. "Code": "F42"})
// Delete -删除 product 删除数据
db.Delete(&product, 1)
}
Notes:
//Transactions by manual
// begin a transaction
tx := db.Begin()
// do some database operations in the transaction (use 'tx' from this point, not 'db')
tx.Create(...)
// ...
// rollback the transaction in case of error
tx.Rollback()
// Or commit the transaction
tx.Commit()
db.Transaction(func(tx *gorm.DB) error {
// do some database operations in the transaction (use 'tx' from this point, not 'db')
if err := tx.Create(&Animal{Name: "Giraffe"}).Error; err != nil {
// return any error will rollback
return err
}
if err := tx.Create(&Animal{Name: "Lion"}).Error; err != nil {
return err
}
// return nil will commit the whole transaction
return nil
})
3. Kitex
生态
4.Hertz
生态
5. 应用实战项目
字节开源项目,整个项目应用了三件套作为开发框架,可供快速入门学习。
easynote
图片均来自字节青训营课程,博客作为自己学习记录,如有侵权,麻烦联系删除。