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);
        }
    }
}
相关推荐
tiancaijiben15 分钟前
阿里云函数计算FC如何实现网站的定时任务与自动化
数据库·oracle·dba
xfhuangfu15 分钟前
Oracle 19c 多租户体系架构介绍
数据库·oracle·架构
java1234_小锋19 分钟前
请描述 Spring Boot 的启动流程,包括 SpringApplication 的初始化和 run 方法的核心步骤。
java·数据库·spring boot
qq_谁赞成_谁反对31 分钟前
甲方IT的成长之路--nginx实战--2604
服务器·数据库·nginx
云水一下38 分钟前
从零开始学 PHP 系列(六):MySQL 数据库与 PHP 交互——让数据真正“住”进服务器
数据库·mysql·php
fofantasy40 分钟前
NSK LH25FL 升级至 NH25EM 技术规格指南
服务器·网络·数据库·经验分享·规格说明书
炘爚42 分钟前
Linux——Redis
数据库·redis·缓存
Oo_行者_oO1 小时前
删库先别跑路,万一修复呢?MySQL 误删数据恢复可落地运维文档
数据库·面试
曾阿伦1 小时前
深入了解MongoDB 两地三中心架构
数据库·mongodb·架构