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);
        }
    }
}
相关推荐
许彰午6 分钟前
03-Linux环境准备依赖包内核参数与用户组
linux·运维·服务器·数据库
阳光九叶草LXGZXJ21 分钟前
达梦数据库-报错-16-MERGE INTO提示:无效的列名[XX]
linux·运维·数据库·sql·学习
墨天梦23 分钟前
B10_文件SharedPreferences与SQLite
jvm·数据库·sqlite
鲲极32 分钟前
居间业务数据统计看板 三条取数口径怎么归一才对得上
数据库·鲲极·鲲极系统
ao-weilai1 小时前
MySQL数据库:基本查询
android·数据库·mysql
java1234_小锋1 小时前
【技术专题】Mysql8 数据库 - Mysql8 查询数据
数据库·mysql
ToddyBear2 小时前
云厂商技术支持部门的原话:元数据库删了,我们也恢复不了[特殊字符]
数据库·产品运营
IanSkunk3 小时前
从检查设备到训练方案:眼科与视光中心设备联动的数据通路、字段口径与校验规则
服务器·数据库·负载均衡
ShineWinsu3 小时前
对于Redis:事务的解析
数据库·redis·mysql·缓存·面试·事务·acid
ao-weilai4 小时前
MySQL数据库:内置函数
android·数据库·mysql