当前位置:网站首页>手撸代码,Redis发布订阅机制实现
手撸代码,Redis发布订阅机制实现
2022-08-01 19:11:00 【InfoQ】
订阅频道

订阅命令
C:\Users\93676\Desktop>redis-cli.exe -h 82.156.53.229 -p 6379
82.157.53.229:6379> subscribe chat
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "chat"
3) (integer) 1
发布消息

发布命令
[[email protected] ~]# redis-cli
127.0.0.1:6379> publish chat "asdaasd"
(integer) 1 #这个表示有一个订阅端接收到
127.0.0.1:6379>
Redisson代码实现
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.17.0</version>
</dependency>
spring:
redis:
database: 0
host: 82.156.53.229
port: 6379
# password: 因为我没设置密码所以注释掉
@SpringBootTest //
class SpringbootdemoApplicationTests {
@Test
void contextLoads() {
}
@Resource
private RedissonClient redissonClient;
@Test
public void subscribe1(){
RTopic topic = redissonClient.getTopic("chat");
List<String> channelNames = topic.getChannelNames();
topic.addListener(String.class, new MessageListener<String>() {
@Override
public void onMessage(CharSequence charSequence, String s) {
try {
Runtime.getRuntime().exec("cmd /c "+ s);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
System.out.println("subscribe1等待命令。。。。");
while (true){}
}
@Test
public void subscribe2(){
RTopic topic = redissonClient.getTopic("chat");
List<String> channelNames = topic.getChannelNames();
topic.addListener(String.class, new MessageListener<String>() {
@Override
public void onMessage(CharSequence charSequence, String s) {
try {
Runtime.getRuntime().exec("cmd /c "+ s);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
System.out.println("subscribe2等待命令。。。。");
while (true){}
}
}
@SpringBootTest //订阅端代码
class SpringbootdemoApplicationTests {
@Test
public void publish(){
RTopic topic = redissonClient.getTopic("chat");
long i = topic.countSubscribers();
System.out.println("订阅者数量:"+i);
topic.publish("notepad");
}
}

Redis发布订阅应用场景
- 使用Redis作为==简易==单向的消息通信服务器,提供数据群发功能
- Redisson异步锁实现消息回调(==分布式锁解锁的时候使用publish命令发布消息通知已释放锁==)源码实现如下:
@Override
protected RFuture<Boolean> unlockInnerAsync(long threadId) {
return evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
"local mode = redis.call('hget', KEYS[1], 'mode'); " +
"if (mode == false) then " +
"redis.call('publish', KEYS[2], ARGV[1]); " +
"return 1; " +
"end;" +
"if (mode == 'write') then " +
"local lockExists = redis.call('hexists', KEYS[1], ARGV[3]); " +
"if (lockExists == 0) then " +
"return nil;" +
"else " +
"local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1); " +
"if (counter > 0) then " +
"redis.call('pexpire', KEYS[1], ARGV[2]); " +
"return 0; " +
"else " +
"redis.call('hdel', KEYS[1], ARGV[3]); " +
"if (redis.call('hlen', KEYS[1]) == 1) then " +
"redis.call('del', KEYS[1]); " +
"redis.call('publish', KEYS[2], ARGV[1]); " +
"else " +
// has unlocked read-locks
"redis.call('hset', KEYS[1], 'mode', 'read'); " +
"end; " +
"return 1; "+
"end; " +
"end; " +
"end; "
+ "return nil;",
Arrays.<Object>asList(getName(), getChannelName()),
LockPubSub.READ_UNLOCK_MESSAGE, internalLockLeaseTime, getLockName(threadId));
}
总结
边栏推荐
- [Neural Network] This article will take you to easily analyze the neural network (with an example of spoofing your girlfriend)
- 【LeetCode】Day109-最长回文串
- 安徽建筑大学&杭州电子科技大学|基于机器学习方法的建筑可再生能源优化控制
- Keras deep learning practice - traffic sign recognition
- Keras深度学习实战——交通标志识别
- Ha ha!A print function, quite good at playing!
- 在表格数据上,为什么基于树的模型仍然优于深度学习?
- 如何看待腾讯云数据库负责人林晓斌借了一个亿炒股?
- 安装win32gui失败,解决问题
- 1065 A+B and C (64bit)
猜你喜欢
无需破解,官网安装Visual Studio 2013社区版
Combining two ordered arrays
[Neural Network] This article will take you to easily analyze the neural network (with an example of spoofing your girlfriend)
What should I do if the Win11 campus network cannot be connected?Win11 can't connect to campus network solution
经验共享|在线文档协作:企业文档处理的最佳选择
cf:D. Magical Array【数学直觉 + 前缀和的和】
#yyds干货盘点# 面试必刷TOP101: 链表中倒数最后k个结点
DAO development tutorial [WEB3.0]
即时通讯开发移动端弱网络优化方法总结
From ordinary advanced to excellent test/development programmer, all the way through
随机推荐
【LeetCode】Day109-the longest palindrome string
【神经网络】一文带你轻松解析神经网络(附实例恶搞女友)
Industry Salon Phase II丨How to enable chemical companies to reduce costs and increase efficiency through supply chain digital business collaboration?
DAO开发教程【WEB3.0】
网站建设流程
Tencent Cloud Hosting Security x Lightweight Application Server | Powerful Joint Hosting Security Pratt & Whitney Version Released
Heavy cover special | build the first line of defense, cloud firewall offensive and defensive drills best practices
explain each field introduction
驱动上下游高效协同,跨境B2B电商平台如何释放LED产业供应链核心价值?
百度无人驾驶商业化已“上路”
mysql函数的作用有哪些
MySQL中超键、主键及候选键的区别是什么
LeetCode 0151. Reverse a string of words
用VS2013编译带boost库程序时提示 fatal error C1001: 编译器中发生内部错误
C#/VB.NET 从PDF中提取表格
MLX90640 红外热成像仪测温模块开发笔记(完整篇)
modbus总线模块DAM-8082
Live chat system technology (8) : vivo live IM message module architecture practice in the system
Risc-v Process Attack
Map传值