登录
首页 >  Golang >  Go问答

将数据库客户端注入到Golang结构中的方法

来源:stackoverflow

时间:2024-03-06 13:09:25 393浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《将数据库客户端注入到Golang结构中的方法》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我正在尝试使用依赖注入来使用go语言将数据库客户端注入到结构中。不幸的是,我不明白这是如何做到的,因为我只在互联网上看到基本的例子,从中我无法获得完整的图片。

我有一个有不同实现的生产者接口。我还有一个用于 redis/kafka 的客户端来生成消息。

package producers

type iproducer interface {
    setmessagetype(messagetype string)
    settopic(topic string)
    getmessagetype() string
    gettopic() string
}

type producer struct {
    messagetype string
    topic       string
}
// producer implements the iproducer

type userlocationproducer struct {
    producer
}

func newuserlocationproducer() iproducer {
    return &userlocationproducer{
        producer: producer{
            messagetype: "user_location",
            topic:       "user_location",
        },
    }
}

redis客户端代码

type RedisClient struct {
    pool *redis.Pool
}

func NewRedisClient(addr string, dn int, passwd string) *RedisClient {
    // code to create client
    return client
}

现在我的问题是,如果我想将 redisclient 注入 producer 中,我该如何实现它。我基本上来自 java 背景,我将使用 spring 来连接我的依赖项并自动装配依赖项。非常感谢任何指点。


正确答案


这里可以通过使用接口来完成依赖注入,这些接口充当不同客户端之间的通用性,例如以下是实现此目的的方法之一。

kafka/redis 客户端都满足的客户端接口

type client interface{
    publish()
}

func (redisclient redisclient) publish(){
    //do client things
}

iproducer:设置客户端的新方法(kafka/redis)。

type iproducer interface {
    ...
    setclient(client client)
}

producer:客户端引用的字段,以及setter方法,

type Producer struct {
    ...
    client Client
}

func (producer Producer)SetClient(clt Client){
    producer.client = clt
}

func (producer Producer)send(){
    client.Publish()
}

可以模拟客户端接口进行测试并以相同的方式注入生产者

此外,在创建 producer 时也可以直接设置 setclient 方法字段 client ,只是 setter 方法提供了更多控制权。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>