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);
        }
    }
}
相关推荐
数据知道23 分钟前
PostgreSQL 故障排查:如何找出数据库中最耗时的 SQL 语句
数据库·sql·postgresql
qq_124987075323 分钟前
基于SSM的动物保护系统的设计与实现(源码+论文+部署+安装)
java·数据库·spring boot·毕业设计·ssm·计算机毕业设计
枷锁—sha24 分钟前
【SRC】SQL注入WAF 绕过应对策略(二)
网络·数据库·python·sql·安全·网络安全
Coder_Boy_29 分钟前
基于SpringAI的在线考试系统-考试系统开发流程案例
java·数据库·人工智能·spring boot·后端
Gain_chance35 分钟前
35-学习笔记尚硅谷数仓搭建-DWS层最近n日汇总表及历史至今汇总表建表语句
数据库·数据仓库·hive·笔记·学习
此生只爱蛋1 小时前
【Redis】主从复制
数据库·redis
马猴烧酒.1 小时前
【面试八股|JAVA多线程】JAVA多线程常考面试题详解
java·服务器·数据库
天天爱吃肉82182 小时前
跟着创意天才周杰伦学新能源汽车研发测试!3年从工程师到领域专家的成长秘籍!
数据库·python·算法·分类·汽车
大巨头2 小时前
sql2008 数据库分页语句
数据库
m0_715575342 小时前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python