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);
        }
    }
}
相关推荐
He.ZaoCha23 分钟前
函数-1-字符串函数
数据库·sql·mysql
二当家的素材网32 分钟前
Centos和麒麟系统如何每天晚上2点10分定时备份达梦数据库
linux·数据库·centos
白仑色38 分钟前
Oracle 存储过程、函数与触发器
数据库·oracle·数据库开发·存储过程·plsql编程
头发那是一根不剩了2 小时前
Spring Boot 多数据源切换:AbstractRoutingDataSource
数据库·spring boot·后端
草履虫建模2 小时前
Redis:高性能内存数据库与缓存利器
java·数据库·spring boot·redis·分布式·mysql·缓存
A-刘晨阳3 小时前
【Linux】Redis 6.2.6 的二进制部署【适用于多版本】
linux·运维·redis
泊浮目3 小时前
未来数据库硬件-计算篇
数据库·云计算·操作系统
靖顺3 小时前
【OceanBase诊断调优】—— 执行计划显示分区 PARTITIONS[P0SP9] 如何查询是哪个分区?
数据库·oracle·oceanbase
KIDAKN4 小时前
MySQL 存储结构
数据库·mysql
Code季风4 小时前
SQL关键字快速入门:HAVING 分组后的条件过滤
数据库·sql·mysql