淺析golang的依賴注入
前言
如果是做web開發(fā),對依賴注入肯定不陌生,java程序員早就習慣了spring提供的依賴注入,做業(yè)務開發(fā)時非常方便,只關注業(yè)務邏輯即可,對象之間的依賴關系都交給框架。
golang是強類型語言,編譯后是機器碼,所以一般使用 反射 或 代碼生成 解決依賴注入的問題
基于反射的DI
基于反射解決DI問題的框架, 使用比較多的是Uber的 dig 庫
官方的例子:
type Config struct { Prefix string } //初始化Config函數(shù) func NewConfig()(*Config, error) { // In a real program, the configuration will probably be read from a // file. var cfg Config err := json.Unmarshal([]byte(`{"prefix": "[foo] "}`), &cfg) return &cfg, err } //初始化logger函數(shù) func NewLogger(cfg *Config) *log.Logger { return log.New(os.Stdout, cfg.Prefix, 0) } func Handle() (l *log.Logger) { l.Print("You've been invoked") } func main() { //初始化dig對象 c := dig.New() //Provide方法用來設置依賴的對象 er := c.Provide(NewConfig) if err != nil { panic(err) } //設置依賴的對象 err = c.Provide(NewLogger) if err != nil { panic(err) } //執(zhí)行Handle()方法 //Handle依賴 Config 和 Logger,使用Invoke執(zhí)行方法時會自動注入依賴(依賴的對象要傳入Provide方法中) err = c.Invoke(Handle) if err != nil { panic(err) } // Output: // [foo] You've been invoked }
dig提供了一個容器(container),所有的依賴項通過Provide方法添加,執(zhí)行某個方法時使用Invoke方法,該方法會自動注入所需要的依賴。
dig使用反射機制解決DI問題,所以代碼執(zhí)行性能上會有損耗
并且因為使用反射所以可能出現(xiàn)編譯時沒有錯誤,執(zhí)行時報空指針
詳情使用方法可以參考官方文檔,dig可以繼承到gin框架中,有興趣的可以看看資料。
筆者不太喜歡這種使用方式,為了依賴注入破壞了代碼原有的調用方式。
基于代碼生成的DI
wire庫是google出的解決golang DI問題的工具,它可以 自動生成依賴注入的代碼,節(jié)省了手動去處理依賴關系
wire對原有代碼的侵入度很低,開發(fā)過程中,在依賴注入代碼處調用Build方法(例子中是初始化controller對象)就可以了
// +build wireinject package main import ( "encoding/json" "fmt" "github.com/google/wire" "net/http" ) type DataSource struct { Operation string } func NewDataSource() DataSource { return DataSource{Operation: "operation_name"} } //================== type Dao struct { DataSource DataSource } func NewDao(ds DataSource) *Dao { return &Dao{ DataSource: ds, } } func (d *Dao) GetItemList() ([]string, error) { //TODO 拿到DB對象做查詢操作 fmt.Printf("db object: %s", d.DataSource.Operation) return []string{d.DataSource.Operation, "item1", "item2"}, nil } //==================== type Service struct { Dao *Dao } func NewService(dao *Dao) *Service { return &Service{Dao: dao} } func (s *Service) GetItemList() ([]string, error) { return s.Dao.GetItemList() } //===================== type Controller struct { Service *Service } func NewController(service *Service) *Controller { return &Controller{Service: service} } func (c *Controller) GetItemList() ([]string, error) { return c.Service.GetItemList() } var MegaSet = wire.NewSet(NewDataSource, NewDao, NewService, NewController) func initializeController() *Controller { wire.Build(MegaSet) return &Controller{} } func getItemList(w http.ResponseWriter, r *http.Request) { controller := initializeController() itemList, _ := controller.GetItemList() output, _ := json.Marshal(itemList) fmt.Fprintf(w, string(output)) } func main() { http.HandleFunc("/items", getItemList) err := http.ListenAndServe(":8080", nil) if err != nil { panic(err) } }
然后再項目根目錄執(zhí)行wire命令,會生成構建好依賴關系的代碼(以_gen結尾的文件)
// Code generated by Wire. DO NOT EDIT. //go:generate go run github.com/google/wire/cmd/wire //+build !wireinject package main import ( "encoding/json" "fmt" "github.com/google/wire" "net/http" ) // Injectors from main.go: // 此處是生成的代碼 func initializeController() *Controller { dataSource := NewDataSource() dao := NewDao(dataSource) service := NewService(dao) controller := NewController(service) return controller } // main.go: type DataSource struct { Operation string } func NewDataSource() DataSource { return DataSource{Operation: "operation_name"} } type Dao struct { DataSource DataSource } func NewDao(ds DataSource) *Dao { return &Dao{ DataSource: ds, } } func (d *Dao) GetItemList() ([]string, error) { fmt.Printf("db object: %s", d.DataSource.Operation) return []string{d.DataSource.Operation, "item1", "item2"}, nil } type Service struct { Dao *Dao } func NewService(dao *Dao) *Service { return &Service{Dao: dao} } func (s *Service) GetItemList() ([]string, error) { return s.Dao.GetItemList() } type Controller struct { Service *Service } func NewController(service *Service) *Controller { return &Controller{Service: service} } func (c *Controller) GetItemList() ([]string, error) { return c.Service.GetItemList() } var MegaSet = wire.NewSet(NewDataSource, NewDao, NewService, NewController) func getItemList(w http.ResponseWriter, r *http.Request) { controller := initializeController() itemList, _ := controller.GetItemList() output, _ := json.Marshal(itemList) fmt.Fprintf(w, string(output)) } func main() { http.HandleFunc("/items", getItemList) err := http.ListenAndServe(":8080", nil) if err != nil { panic(err) } }
關鍵代碼:
//執(zhí)行wire命令前的代碼 func initializeController() *Controller { wire.Build(MegaSet) return &Controller{} } //執(zhí)行后生成的代碼 // Injectors from main.go: func initializeController() *Controller { dataSource := NewDataSource() dao := NewDao(dataSource) service := NewService(dao) controller := NewController(service) return controller }
通過生成代碼解決依賴注入的問題,既能提升開發(fā)效率,又不影響代碼性能,wire更高級的用法可以去github document查看
- tips: 如果報錯誤
other declaration of xxxx
,請在源文件頭加上//+build wireinject
- go-zero框架也是用wire解決DI問題
到此這篇關于淺析golang的依賴注入的文章就介紹到這了,更多相關go依賴注入內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解Golang利用反射reflect動態(tài)調用方法
這篇文章主要介紹了詳解Golang利用反射reflect動態(tài)調用方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-11-11Golang中goroutine和channel使用介紹深入分析
一次只做一件事情并不是完成任務最快的方法,一些大的任務可以拆解成若干個小任務,goroutine可以讓程序同時處理幾個不同的任務,goroutine使用channel來協(xié)調它們的工作,channel允許goroutine互相發(fā)送數(shù)據(jù)并同步,這樣一個goroutine就不會領先于另一個goroutine2023-01-01詳解如何在golang項目開發(fā)中創(chuàng)建自己的Module
既然我們使用了很多開源的 module為我們的日常開發(fā)提供了很多的便捷性,那我們該如何實現(xiàn)自己的 module 來提供給團隊中使用,接下小編就給大家介紹一下在golang項目開發(fā)如何創(chuàng)建自己的Module,需要的朋友可以參考下2023-09-09