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);
        }
    }
}
相关推荐
程序边界1 分钟前
MongoDB迁移到KES实战全纪录(上):迁移准备与实施指南
数据库·mongodb
weixin_4211334110 分钟前
django xadmin 结合 minio
数据库·django·sqlite
zl97989928 分钟前
Redis-缓存问题(穿透、击穿、雪崩)
redis
白云偷星子31 分钟前
MySQL笔记14
数据库·笔记·mysql
绵绵细雨中的乡音1 小时前
MySQL 常用函数实操指南:从基础到实战案例
数据库·mysql
凉栀お_2 小时前
MySQL相关知识查询表中内容(第二次作业)
数据库·mysql
ss2733 小时前
手写Spring第7弹:Spring IoC容器深度解析:XML配置的完整指南
java·前端·数据库
PFinal社区_南丞3 小时前
PostgreSQL-10个鲜为人知的强大功能
数据库·后端
misty youth3 小时前
配置openguass 教程(自存)
数据库·ubuntu·华为·openguass
瑞士卷@4 小时前
MyBatis入门到精通(Mybatis学习笔记)
java·数据库·后端·mybatis