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);
        }
    }
}
相关推荐
λqaq725 分钟前
MySQL 数据库基础(2)约束、用户权限、远程连接、外键与 TCP/UDP 理解
linux·数据库·python·tcp/ip·mysql
丰锋ff25 分钟前
基于C++11的数据库连接池
数据库
TDengine (老段)32 分钟前
TDengine 应用案例 — 工业大数据与智能制造
大数据·数据库·制造·时序数据库·tdengine·涛思数据
狂热开发者36 分钟前
打印机卖到欧洲以后 App 更新了,旧包装二维码还能用吗
数据库
张3蜂1 小时前
2026 中国国产数据库 Top 20:市场格局、开源协议与竞品分析
数据库
烟雨归来1 小时前
Oracle 19c RAC登录风暴引发library cache lock生产故障分析
数据库·oracle
longxiaozhang61 小时前
C#异常处理:程序出错了怎么办?
开发语言·数据库·c#
NineData2 小时前
DTCC 2026 NineData 叶正盛:如何统一管理人与 AI Agent 的数据访问行为
数据库·人工智能·sql·oracle·agent·ninedata·dtcc
一入程序无退路2 小时前
Navicat导出Excel格式表名表结构
数据库·excel
记忆张量MemTensor2 小时前
MemOS Skill 上线|一句话即可接入 MemOS Cloud
大数据·数据库·人工智能·typescript·开源