英文:
Golang RPC and dependencies
问题
我有两个golang后端,每个后端都有自己的层次结构,如下所示:
- API层
- 服务层
- 数据层
我将应用程序的依赖项(如数据库连接)注入到数据层,并从API到服务再到数据构建层次结构。因此,当应用程序启动时,我将注入包含所有运行时依赖项(包括数据库连接)的应用程序结构体。
一切都按预期工作。
但是,对于新功能,我需要在第一个后端上实现RPC服务器,并在第二个后端上实现RPC客户端。
//app.go
package app
type App struct {
dbconn *redis.Client
}
//main.go
package main
func main() {
myService := new(service.MyService)
err := rpc.Register(myService)
.
.
.
}
现在,在一个后端上我有运行中的RPC服务器,并且我有以下方法:
// myservice.go go
package service
type MyService struct {
App: app
}
type NewMyService(app App) MyService {
return MyService { App: app }
}
func (s MyService) getData() {
s.app.dbconn.Get(....)
fmt.Println(app) // 0xc0005229e0
}
func (s MyService) GetDataForExternalRequests(key string, res *string) {
// 现在在这里我无法访问s.app.dbconnection(它是nil)
fmt.Println(app) // <nil>
}
在GetDataForExternalRequests方法中,我如何访问app对象?
英文:
I have two golang backends, which each has its own layers as following:
- API layer
- Service layer
- Data layer
I am enjecting the app dependencies like db connection to the data layer, and constructing the layers from API to service then data. so when the app starts I will enject the app struct which is contain all depencies for runtime including db connection.
everything works as expected.
but for the new feature I need to implement RPC server on first backend and RPC client on the second one.
//app.go
package app
type App struct {
dbconn *redis.Client
}
//main.go
package main
func main() {
myService := new(service.MyService)
err := rpc.Register(myService)
.
.
.
}
Now in one backend I have rpc server running and i have the following method:
// myservice.go go
package service
type MyService struct {
App: app
}
type NewMyService(app App) MyService {
return MyService { App: app }
}
func (s MyService) getData() {
s.app.dbconn.Get(....)
fmt.Println(app) // 0xc0005229e0
}
func (s MyService) GetDataForExternalRequests(key string, res *string) {
// now here I don't have access to s.app.dbconnection (it is nil)
fmt.Println(app) // <nil>
}
in the GetDataForExternalRequests How can I access the app object ?
答案1
得分: 1
实际上,我弄清楚了,在main.go
中,当我创建myService
时,我不应该使用new
关键字,或者如果我使用了它,那么我必须先构造它,然后才能注册它,所以有两种解决方案:
- 解决方案1:
myService := service.MyService
err := rpc.Register(myService)
- 解决方案2:
myService := service.NewMyService(app)
err := rpc.Register(myService)
英文:
Actually I figured out, in main.go
when I am creating myService
I shouldn'nt use new
keyword or if I used it then Ihave to constructed first then I can register it so:
- solution 1:
myService := service.MyService
err := rpc.Register(myService)
- solution 2:
myService := service.NewMyService(app)
err := rpc.Register(myService)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论