redis的发布与订阅

与消息队列的差别

不做持久化

不是异步

不能保证可靠性

使用实例

发布者示例:连接到 Redis 服务器,使用 publish 方法发布消息到指定的频道。

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

使用lettuce的示例

发布者:

csharp 复制代码
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();
    }
}

订阅者:

csharp 复制代码
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);
        }
    }
}
相关推荐
这个DBA有点耶21 小时前
2026下半年数据库趋势:多模、云原生、AI融合
数据库·人工智能·云原生
l1t21 小时前
DeepSeek总结的从 Crunchy PGO 迁移到使用 CloudNativePG 管理的 PostgreSQL 18
数据库·postgresql
夜雪闻竹21 小时前
Claude Code 对话自动导入完全指南
数据库·数据挖掘·copilot
恼书:-(空寄21 小时前
缓存:Redis7.0+、多级缓存设计、缓存三大问题解决方案
redis·缓存
云祺vinchin1 天前
云祺x鼎捷,为制造企业ERP打造双保险
数据库·安全·制造
我滴老baby1 天前
2026年AI Agent将走向何方?十大趋势深度解析:从多模态融合到自主决策,从端侧部署到具身智能,提前布局下一个万亿级市场
数据库·人工智能·知识图谱
AC赳赳老秦1 天前
OpenClaw与思维导图工具联动:自动生成工作规划脑图、拆解任务节点,适配职场管理
java·大数据·服务器·数据库·python·php·openclaw
IronMurphy1 天前
Redis拷打第六讲
redis·spring·mybatis
zhishijike1 天前
全国行政区划sql(省市区)
数据库·sql·mysql
早川9191 天前
Hbase、MySQL和Redis区别
redis·mysql·hbase