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);
        }
    }
}
相关推荐
2201_75684733几秒前
如何设置备库只接日志不应用_暂停MRP且维持网络传输的方法
jvm·数据库·python
dualven_in_csdn6 分钟前
EMQX 开启 **MySQL + password_based** 认证
android·数据库·mysql
Jul1en_12 分钟前
【Redis】单线程模型
数据库·redis·缓存
Arva .15 分钟前
Spring 事务传播机制 速记
java·数据库·spring
东北甜妹18 分钟前
Redis Cluster 部署
前端·javascript·bootstrap
hef28819 分钟前
如何查找SQL字符串中字符数_掌握CHAR_LENGTH应用
jvm·数据库·python
木心术126 分钟前
Web安全攻防实战:常见漏洞分析与防御策略
网络·数据库·web安全
熬夜的咕噜猫29 分钟前
LVS+Keepalived高可用群集
大数据·网络·数据库·mysql·mysql高可用
残 风32 分钟前
事务并发机制之两阶段锁篇
数据库·postgresql·开源·数据库开发
淼淼爱喝水34 分钟前
SQL注入漏洞检测与修复
数据库·sql