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);
        }
    }
}
相关推荐
2301_781392523 分钟前
MySQL格式化数据展示——分页查询
java·数据库·mysql·性能优化
va学弟9 分钟前
SQL 进阶知识——多表关联与约束
数据库·sql
L16247620 分钟前
Nginx+Tomcat+Redis(单节点 / 3 节点集群)+Redisson 共享 Session 完整整合手册
redis·nginx·tomcat
一 乐24 分钟前
学生宿舍管理|基于springboot + vue学生宿舍管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·助农电商系统
heze0935 分钟前
sqli-labs-Less-23
数据库·mysql·网络安全
米汤爱学习36 分钟前
Redis-漏洞
数据库·redis·缓存
像少年啦飞驰点、42 分钟前
零基础入门 Redis:从“缓存是什么”到手写一个简易购物车系统
java·spring boot·redis·缓存·编程入门·小白教程
wWYy.1 小时前
详解redis(7):数据结构List
数据库·redis·缓存
砚边数影1 小时前
时序数据库国产化替代,破局迁移“三不”困局
数据库·时序数据库·kingbase·kingbasees·金仓数据库
专注于大数据技术栈1 小时前
Redis 中 USED 和 RSS
数据库·redis·缓存