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);
        }
    }
}
相关推荐
我是人✓9 分钟前
SQL主键与外键
java·数据库
飞翔的馒9 分钟前
浏览器缓存之【结构化数据库与缓存】: IndexedDB、Cache storage 和 Storage buckets
数据库·缓存
SelectDB11 分钟前
SelectDB search():AI 日志搜索与分析场景的技术能力与实践
数据库
SelectDB14 分钟前
Apache Doris 事务保障:技术能力、选型对比与企业实践
数据库
SelectDB17 分钟前
AI Observe Stack(基于 Apache Doris):AI Agent 可观测性技术能力、选型对比与实践
数据库
SelectDB25 分钟前
PostgreSQL + Apache Doris HTAP 架构:技术能力、选型对比与企业实践
数据库
SelectDB26 分钟前
SelectDB(飞轮科技)技术研发型企业认证:Apache Doris 核心能力、选型对比与实践
数据库
古月方枘Fry26 分钟前
基于大模型+MySQL的innoai助手(可适配多数环境)
网络·数据库·mysql·aigc
Databend43 分钟前
从全表排序到概率统计:Databend 如何用 KLL、Top-N 与 CMS 改进基数估计
大数据·数据库·算法