redis container发布订阅 代码配置
时间: 2023-09-12 22:08:24 浏览: 51
好的,这是 Redis Docker 容器中发布订阅的代码配置示例:
首先,我们需要启动一个 Redis Docker 容器。可以使用以下命令:
```
docker run -d -p 6379:6379 --name redis redis
```
这个命令将在后台运行 Redis 容器,并将容器的 6379 端口映射到主机的 6379 端口。我们可以使用以下命令来验证容器是否已经启动:
```
docker ps
```
接下来,在订阅者端,我们可以使用 Jedis 的 subscribe() 方法来订阅一个或多个频道,例如:
```
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
public class Subscriber {
public static void main(String[] args) {
Jedis jedis = new Jedis("localhost", 6379);
jedis.subscribe(new JedisPubSub() {
@Override
public void onMessage(String channel, String message) {
System.out.println(String.format("Received message: %s from channel: %s", message, channel));
}
}, "channel1", "channel2");
}
}
```
在这个示例中,我们使用 Jedis 的 subscribe() 方法来订阅两个频道:channel1 和 channel2。我们使用匿名内部类来实现 JedisPubSub 类的 onMessage() 方法,该方法用于处理接收到的消息,并将其打印到控制台上。在连接 Redis 服务器时,我们需要指定连接的主机和端口,这里我们使用了默认的主机 localhost 和容器映射到主机的端口 6379。
接下来,在发布者端,我们可以使用 Jedis 的 publish() 方法来向指定频道发布消息,例如:
```
import redis.clients.jedis.Jedis;
public class Publisher {
public static void main(String[] args) {
Jedis jedis = new Jedis("localhost", 6379);
jedis.publish("channel1", "hello, world!");
}
}
```
在这个示例中,我们同样使用 Jedis 的 publish() 方法来向频道 channel1 发布一条消息:hello, world!。在连接 Redis 服务器时,我们同样需要指定连接的主机和端口。
需要注意的是,在 Docker 容器中使用 Redis 发布订阅时,订阅者和发布者需要连接到容器的 IP 地址和映射到主机的端口。可以使用以下命令来查找容器的 IP 地址:
```
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' redis
```
其中 redis 是容器的名称。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)