Py学习  »  Redis

使用Redis作为Docker容器之间的链接

henleyhoudini • 6 年前 • 1381 次点击  

我有一个docker compose文件,里面有几个容器,其中两个应该通过Redis DB通信。两个容器都有到里德的连接,我可以从这两个容器读/写。不过,我希望每次从另一个容器添加内容时都触发一个容器。我想我可以通过Redis Sub/Pub来实现这一点,但是当我运行代码时,它不会触发任何东西,即使我可以看到我已经向Redis队列添加了新项。

我有两个问题: 一。我想做的是可能的吗?我可以在两个独立的docker容器中发布/订阅并期望它按上述方式工作吗? 2。如果可能的话,有人能给我指一下我用这个工具哪里出错了吗?

这是我的功能,我添加新的数据到Redis队列,然后在Docker容器1中发布数据。

func redisShare(key string, value string) {
jobsQueue.Set(key, value, 0) //setting in the queue
jobsQueue.Publish(key, value) //publishing for the other docker container to notice
fmt.Println("added ", key, "with a value of ", value, "to the redis queue")
}

我正在我的另一个docker容器中使用这一行订阅Redis队列并侦听更改: redisdb.Subscribe()

如果有东西被添加到redis队列中,它会将数据共享给另一个容器,我会看到收到的消息,但是现在Docker容器2只是运行然后关闭。

谢谢!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52726
文章 [ 2 ]  |  最新文章 6 年前
Aleksandrs Antonovs
Reply   •   1 楼
Aleksandrs Antonovs    7 年前

docs

接收器。开始

package main

import (
    "fmt"

    "github.com/go-redis/redis"
)

func main() {
    c := redis.NewClient(&redis.Options{
        Addr: ":6379",
    })

    pubsub := c.Subscribe("mychannel1")

    // Wait for confirmation that subscription is created before publishing anything.
    _, err := pubsub.Receive()
    if err != nil {
        panic(err)
    }

    // Go channel which receives messages.
    ch := pubsub.Channel()

    // Consume messages.
    for msg := range ch {
        fmt.Println(msg.Channel, msg.Payload)
    }
}

发件人.go

package main

import (
    "time"

    "github.com/go-redis/redis"
)

func main() {
    c := redis.NewClient(&redis.Options{
        Addr: ":6379",
    })

    // Publish a message.
    for range time.Tick(time.Second) {
        err := c.Publish("mychannel1", "hello").Err()
        if err != nil {
            panic(err)
        }
    }
}
henleyhoudini
Reply   •   2 楼
henleyhoudini    7 年前

以防其他人对答案产生疑问:我最终使用了Aleksandrs和sui的答案的组合。 在我的第一个Docker容器中,我将结果发布到一个特定的频道:

publishData := redisdb.Subscribe("CHANNELNAME")

然后在我订阅频道的第二个Docker容器中,由于sui在这方面的帮助,我订阅了频道并提取了UID和IP信息,如下所示:

ch := pubsub.Channel()
    for msg := range ch {
        fmt.Println(msg.Payload)
        s := strings.Split(msg.Payload, ":")
        UID, IP := s[0], s[1]
        fmt.Println(UID, IP)
    }

到目前为止,这对我来说非常有用——非常感谢sui和Aleksandrs的帮助!