redis实现发布(订阅)消息

什么是redis的发布订阅(pub/sub)?   Pub/Sub功能(means Publish, Subscribe)即发布及订阅功能。基于事件的系统中,Pub/Sub是目前广泛使用的通信模型,它采用事件作为基本的通信机制,提供大规模系统所要求的松散耦合的交互模式:订阅者(如客户端)以事件订阅的方式表达出它有兴趣接收的一个事件或一类事件;发布者(如服务器)可将订阅者感兴趣的事件随时通知相关订阅者。熟悉设计模式的朋友应该了解这与23种设计模式中的观察者模式极为相似。

看到发布订阅的特性,用来做一个简单的实时聊天系统再适合不过了。这是其中之一,当然这样的东西,我们开发中很少涉及到。再举一个常用的,在我们的分布式架构中,常常会遇到读写分离的场景,在写入的过程中,就可以使用redis发布订阅,使得写入值及时发布到各个读的程序中,就保证数据的完整一致性。再比如,在一个博客网站中,有100个粉丝订阅了你,当你发布新文章,就可以推送消息给粉丝们拉。总之场景很多,需要去挖掘。。

Redis的pub/sub是一种消息通信模式,主要的目的是解除消息发布者和消息订阅者之间的耦合,  Redis作为一个pub/sub的server, 在订阅者和发布者之间起到了消息路由的功能。

Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。

Redis 客户端可以订阅任意数量的频道。

当有新消息通过 PUBLISH 命令发送给频道 channel1 时, 这个消息就会被发送给订阅它的所有客户端。

// *************************************************************************** }
//
// Delphi REDIS Client
//
// Copyright (c) 2015-2017 Daniele Teti
//
// https://github.com/danieleteti/delphiredisclient
//
// ***************************************************************************
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// *************************************************************************** unit MainForm; interface uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, redis.client, redis.commons,
redis.netlib.indy, System.threading,
Vcl.StdCtrls; type
TForm2 = class(TForm)
Memo1: TMemo;
Edit2: TEdit;
Label1: TLabel;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Edit2KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Button1Click(Sender: TObject);
private
_redis: IRedisClient;
FTask: ITask;
FClosing: Boolean;
procedure SendChatMessage;
procedure OnMessage(const ANickName, AMessage: string);
{ Private declarations }
public
{ Public declarations }
end; var
Form2: TForm2; implementation uses System.json, ShellAPI;
{$R *.dfm} procedure TForm2.Button1Click(Sender: TObject);
begin
ShellExecute(0, pchar('open'), pchar(Application.ExeName), nil, nil, SW_SHOW);
end; procedure TForm2.Edit2KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_RETURN then
begin
SendChatMessage;
Key := 0;
Edit2.Clear;
end;
end; procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FClosing := True;
end; procedure TForm2.FormCreate(Sender: TObject);
begin
FClosing := False;
Label1.Caption := InputBox('Chat user name',
'What is your user name in this chat?', 'd.teti' + (100 + Random(999))
.ToString);
_redis := NewRedisClient();
FTask := TTask.Run(
procedure
var
r: IRedisClient;
begin
r := NewRedisClient;
r.SUBSCRIBE(['chat'],
procedure(channel, message: string)
var
jobj: TJSONObject;
msg, nickname: string;
begin
jobj := TJSONObject.ParseJSONValue(message) as TJSONObject;
nickname := jobj.GetValue<TJSONString>('nickname').Value;
msg := jobj.GetValue<TJSONString>('message').Value;
TThread.Synchronize(nil,
procedure
begin
Self.OnMessage(nickname, msg);
end);
end,
function: Boolean
begin
Result := Assigned(Self) and (not FClosing);
end);
end);
end; procedure TForm2.OnMessage(const ANickName, AMessage: string);
begin
Memo1.Lines.Add('[' + ANickName + '] ' + DateTimeToStr(now));
Memo1.Lines.Add(AMessage);
Memo1.Lines.Add('---');
end; procedure TForm2.SendChatMessage;
var
jobj: TJSONObject;
begin
jobj := TJSONObject.Create;
try
jobj.AddPair('nickname', Label1.Caption).AddPair('message', Edit2.Text);
_redis.PUBLISH('chat', jobj.ToString);
finally
jobj.Free;
end;
end; end.

  

redis实现发布(订阅)消息的更多相关文章

  1. 【springboot】【redis】springboot+redis实现发布订阅功能,实现redis的消息队列的功能

    springboot+redis实现发布订阅功能,实现redis的消息队列的功能 参考:https://www.cnblogs.com/cx987514451/p/9529611.html 思考一个问 ...

  2. redis的发布订阅模式

    概要 redis的每个server实例都维护着一个保存服务器状态的redisServer结构 struct redisServer {     /* Pubsub */     // 字典,键为频道, ...

  3. StackExchange.Redis 使用-发布订阅 (二)

    使用Redis的发布订阅功能 redis另一个常见的用途是发布订阅功能 . 它非常的简单 ,当连接失败时 ConnectionMultiplexer 会自动重新进行订阅 . ISubscriber s ...

  4. .net core 使用Redis的发布订阅

    Redis是一个性能非常强劲的内存数据库,它一般是作为缓存来使用,但是他不仅仅可以用来作为缓存,比如著名的分布式框架dubbo就可以用Redis来做服务注册中心.接下来介绍一下.net core 使用 ...

  5. java实现 redis的发布订阅(简单易懂)

    redis的应用场景实在太多了,现在介绍一下它的几大特性之一   发布订阅(pub/sub). 特性介绍: 什么是redis的发布订阅(pub/sub)?   Pub/Sub功能(means Publ ...

  6. spring boot 使用redis进行发布订阅

    异步消息的方式有很多,这篇博客介绍如何使用redis进行发布订阅, 完成这个示例只需要三个文件 1.redis消息监听配置 @Configuration public class RedisListe ...

  7. Redis之发布订阅

    一 什么是发布订阅 发布订阅模式又叫观察者模式,它定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都将得到通知 Redis 发布订阅(pub/sub)是一种消息通信模式: ...

  8. 13、Redis的发布订阅模式

     写在前面的话:读书破万卷,编码如有神 -------------------------------------------------------------------------------- ...

  9. [翻译] C# 8.0 新特性 Redis基本使用及百亿数据量中的使用技巧分享(附视频地址及观看指南) 【由浅至深】redis 实现发布订阅的几种方式 .NET Core开发者的福音之玩转Redis的又一傻瓜式神器推荐

    [翻译] C# 8.0 新特性 2018-11-13 17:04 by Rwing, 1179 阅读, 24 评论, 收藏, 编辑 原文: Building C# 8.0[译注:原文主标题如此,但内容 ...

  10. redis(3)发布订阅

    一.发布/订阅模式 在软件工程里面,发布/订阅是一种消息模式,这种模式旨在将消息发送者和消息接收者解耦.发送者不需要关心将消息发送给谁,接收者也不需要知道消息的发送者是谁.发送者将消息发布以后就结束动 ...

随机推荐

  1. jquery实现模拟select下拉框效果

    <IGNORE_JS_OP style="WORD-WRAP: break-word"> <!DOCTYPE html PUBLIC "-//W3C// ...

  2. LeetCode(18):四数之和

    Medium! 题目描述: 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 t ...

  3. Java 组合

    组合: 在新类中产生现有类的对象,由于新的类是由现有类的对象所组成,所以这种方法称为组合 组合和继承都允许在新的类中放置对象,组合时显示的这样做,而继承则是隐式的这样做 组合技术通常用于想在新类中使用 ...

  4. java判断部署项目使用的服务器类型

    有两种方式 1.项目引入portal-kernel.jar.项目运行时使用 根据返回boolean值判断类型! 2.自己写java类 package webService.ZFGX.service; ...

  5. 一些计数小Trick

    一些计数小Trick 虽然说计数问题如果不是特别傻逼的话想做出来基本随缘. 但是掌握一些基本的计数方法还是十分有必要的. 想到了就更新. 1. 对于排列的DP问题,一般是不能够按照位置一个一个放的,一 ...

  6. MapReduce原理1

    Mapreduce是一个分布式运算程序的编程框架,是用户开发“基于hadoop的数据分析应用”的核心框架: Mapreduce核心功能是将用户编写的业务逻辑代码和自带默认组件整合成一个完整的分布式运算 ...

  7. ERROR 2003 (HY000): Can't connect to MySQL server on "192.168.xxx.xxx" (111)

    mac  homebrew 安装的mysql5.6 除本机外无法被其他ip的电脑访问. 网上查原因 有几个: 1.my.cnf配置中 查看是否有   bind-address = 127.0.0.1  ...

  8. 【noip模拟赛1】古韵之鹊桥相会(最短路)

    描述 迢迢牵牛星,皎皎河汉女. 纤纤擢素手,札札弄机杼: 终日不成章,泣涕零如雨. 河汉清且浅,相去复几许? 盈盈一水间,脉脉不得语. ——<古诗十九首> 传说,上古时期的某个七月七日,王 ...

  9. 002 jquery基本选择器

    1.选择器 2.基本选择器 3.程序(包含以上五种基本选择器) <!DOCTYPE html> <html> <head> <meta charset=&qu ...

  10. Python装饰器进阶

    装饰器进阶 现在,我们已经明白了装饰器的原理.接下来,我们还有很多事情需要搞清楚.比如:装饰带参数的函数.多个装饰器同时装饰一个函数.带参数的装饰器和类装饰器. 装饰带参数函数 def foo(fun ...