当前位置:网站首页>手撸代码,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));
}
总结
边栏推荐
- How to query database configuration parameters in GBase 8c, such as datestyle.What function or syntax to use?
- 选择合适的 DevOps 工具,从理解 DevOps 开始
- Write code anytime, anywhere -- deploy your own cloud development environment based on Code-server
- Hardware Bear Original Collection (Updated 2022/07)
- Win11如何删除升级包?Win11删除升级包的方法
- Library website construction source code sharing
- 在GBase 8c数据库后台,使用什么样的命令来对gtm、dn节点进行主备切换的操作?
- SQL function TO_DATE (2)
- PHP 安全最佳实践
- 【全民编程】《软件编程-讲课视频》【零基础入门到实战应用】
猜你喜欢

kubernetes - deploy nfs storage class

Combining two ordered arrays

Screen: GFF, OGS, Oncell, Incell of full lamination process

在Map传值与对象传值中模糊查询

使用常见问题解答软件的好处有哪些?

PanGu-Coder:函数级的代码生成模型

Website construction process
![[Kapok] #Summer Challenge# Hongmeng mini game project - Sudoku (3)](/img/8d/4f5f7c2463b781cba1c68370d3c29c.png)
[Kapok] #Summer Challenge# Hongmeng mini game project - Sudoku (3)

LeetCode 0152. Product Maximum Subarray: dp + Roll in Place

MySQL数据库————存储过程和函数
随机推荐
Combining two ordered arrays
Screen: GFF, OGS, Oncell, Incell of full lamination process
重保特辑|拦截99%恶意流量,揭秘WAF攻防演练最佳实践
explain 各字段介绍
SENSORO成长伙伴计划 x 怀柔黑马科技加速实验室丨以品牌力打造To B企业影响力
shell脚本专题(07):文件由cfs到bos
log factory (detail)
LeetCode 1374. Generate an odd number of each character string
硬件大熊原创合集(2022/07更新)
LeetCode 0152. 乘积最大子数组:dp + 原地滚动
从普通进阶成优秀的测试/开发程序员,一路过关斩将
开源视界 | StreamNative 盛宇帆:和浪漫的人一起做最浪漫的事
对于web性能优化我有话说!
英国伦敦大学|眼科强化学习:潜在应用和实施挑战
在全志V853开发板试编译QT测试
Heavy cover special | build the first line of defense, cloud firewall offensive and defensive drills best practices
odoo 编码规范(编程规范、编码指南)
GZIPOutputStream 类源码分析
日志工厂(详细)
【LeetCode】Day109-最长回文串