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);
        }
    }
}
相关推荐
_codemonster1 小时前
PreparedStatement 和 Statement的区别
数据库·oracle
恒云客1 小时前
python uv debug launch.json
数据库·python·json
愈努力俞幸运2 小时前
第5章数据库,实体关系图,ER图
数据库·oracle
锥栗3 小时前
【其他】基于Trae的大模型智能应用开发
android·java·数据库
qq_353737543 小时前
安全跳转页(用于网站内链,优化SEO)—炫酷特效黑客风格版
数据库·安全
yangyanping201083 小时前
微服务设计之带过期时间的积分系统
数据库
I'mAlex3 小时前
金仓数据库平替MongoDB实操解析:多模融合赋能企业文档数据管理国产化升级
数据库·mongodb·kingbasees·金仓数据库
Pocker_Spades_A3 小时前
MongoDB 远程连不上?用cpolar告别局域网束缚,跨网访问就这么简单
数据库·mongodb
鸽芷咕3 小时前
从底层到实战,金仓多模数据库 MongoDB 兼容的技术实力到底有多强?
数据库·mongodb·金仓数据库
王家视频教程图书馆4 小时前
开源api
数据库