redis的发布与订阅

与消息队列的差别

不做持久化
不是异步
不能保证可靠性

使用实例

发布者示例:连接到 Redis 服务器,使用 publish 方法发布消息到指定的频道。
订阅者示例:连接到 Redis 服务器,使用 subscribe 方法订阅指定的频道,并通过回调或循环处理接收到的消息。

使用lettuce的示例

发布者:

public class LettucePublisher {

    public static void main(String[] args) {
        // 连接到 Redis 服务器
        RedisClient redisClient = RedisClient.create("redis://localhost:6379");
        StatefulRedisConnection<String, String> connection = redisClient.connect();
        RedisCommands<String, String> commands = connection.sync();

        // 发布消息到频道
        String channel = "my_channel";
        String message = "Hello, Redis!";
        commands.publish(channel, message);

        System.out.println("Message '" + message + "' published to channel '" + channel + "'");

        // 关闭连接
        connection.close();
        redisClient.shutdown();
    }
}

订阅者:

public class LettuceSubscriber {

    public static void main(String[] args) {
        // 连接到 Redis 服务器
        RedisClient redisClient = RedisClient.create("redis://localhost:6379");
        StatefulRedisPubSubConnection<String, String> pubSubConnection = redisClient.connectPubSub();
        RedisPubSubCommands<String, String> pubSubCommands = pubSubConnection.sync();

        // 订阅频道
        String channel = "my_channel";
        pubSubCommands.subscribe(channel);

        System.out.println("Subscribed to channel '" + channel + "'");

        // 处理接收到的消息
        while (true) {
            String message = pubSubCommands.receive().getMessage();
            System.out.println("Received message: " + message);
        }
    }
}

相关推荐

  1. redis发布订阅

    2024-07-13 04:46:02       26 阅读
  2. Redis-发布订阅

    2024-07-13 04:46:02       41 阅读
  3. redis订阅发布功能

    2024-07-13 04:46:02       27 阅读
  4. Redis发布-订阅模式之Channel发布订阅

    2024-07-13 04:46:02       31 阅读
  5. Redis使用手册之发布订阅

    2024-07-13 04:46:02       28 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-13 04:46:02       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-13 04:46:02       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-13 04:46:02       58 阅读
  4. Python语言-面向对象

    2024-07-13 04:46:02       69 阅读

热门阅读

  1. Vue Router 4:构建高效单页面应用的路由管理

    2024-07-13 04:46:02       25 阅读
  2. c++【入门】病狗问题

    2024-07-13 04:46:02       22 阅读
  3. UE5 04-重新加载当前场景

    2024-07-13 04:46:02       25 阅读
  4. 【泛型】学习笔记

    2024-07-13 04:46:02       28 阅读
  5. python之修饰器介绍及示例

    2024-07-13 04:46:02       20 阅读
  6. 力扣1717.删除子字符串的最大得分

    2024-07-13 04:46:02       27 阅读
  7. 说一下你对dom驱动和数据驱动的理解

    2024-07-13 04:46:02       25 阅读
  8. GESP CCF C++ 一级认证真题 2024年6月

    2024-07-13 04:46:02       28 阅读