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);
        }
    }
}
相关推荐
PD我是你的真爱粉41 分钟前
MySQL8新特性
数据库·mysql
shalou29011 小时前
Spring 核心技术解析【纯干货版】- Ⅶ:Spring 切面编程模块 Spring-Instrument 模块精讲
前端·数据库·spring
大猫子的技术日记1 小时前
2025 AI Agent 开发实战指南:从上下文工程到多智能体协作
前端·人工智能·bootstrap
eWidget1 小时前
政务电子证照系统重构:如何解决跨模态数据的“一致性”与“安全合规”难题?
数据库·mongodb·kingbase·数据库平替用金仓·金仓数据库·文档数据库
芝士爱知识a3 小时前
【FinTech前沿】AlphaGBM:重塑期权交易的智能分析引擎——从原理到实践
数据结构·数据库·人工智能·alphagbm·期权
AC赳赳老秦3 小时前
2026主权AI趋势:DeepSeek搭建企业自有可控AI环境,保障数据安全实战
大数据·数据库·人工智能·python·科技·rabbitmq·deepseek
仍然.3 小时前
MYSQL---事务
数据库·mysql
king_harry3 小时前
openGauss 6.0 主备集群备份与恢复实战指南:基于 gs_probackup
数据库·opengauss·gs_probackup
ruxshui3 小时前
MySQL备份核心指南
数据库·mysql
PD我是你的真爱粉3 小时前
Redis持久化、内存管理、慢查询与发布订阅
redis·python·mybatis