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);
        }
    }
}
相关推荐
龙腾AI白云1 小时前
具身智能的空间导航与未知环境探索
大数据·数据库·人工智能·机器学习·知识图谱
ClouGence1 小时前
DBeaver太重,Navicat付费?试试这4款好用的开源数据库管理工具!
数据库·开源
字节跳动数据库2 小时前
火山引擎缓存数据库:如何构建超大规模缓存集群的无感弹性能力
数据库·人工智能·后端
SelectDB2 小时前
多模态检索用什么数据库?向量、全文与 SQL 混合检索选型指南
数据库
旋风菠萝3 小时前
HashMap和CurrentHashMap的key可以为空吗
java·数据库·redis
隔窗听雨眠4 小时前
数据管理系统弹性调度的资源模型与实战路径
数据库·分布式系统·弹性调度
Nturmoils4 小时前
数据库选型 POC:订单系统怎么验收候选
数据库
CoderYanger6 小时前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第一弹)
java·数据库·spring·面试·java-ee·tomcat·mybatis
IT规划师11 小时前
Redis 核心机制 | 内存淘汰策略全解:8种策略、近似LRU采样、LFU计数器
redis·.net