Pub/Sub

Publish

Publish done by redis client publish method
1
publish(channel: string, value: string): Promise<number>;
Copied!

Example

1
RedisProvider.GetConnection().publish("room-1", "data");
Copied!

Subscribe

The subscription done by a single method that returns an observable object of type PubSubMessage
1
public getSubscriber<DataType>(byPattern: boolean, channelOrPattern: string): Observable<PubSubMessage<DataType>>
Copied!
PubSubMessage class
1
{
2
hasError: boolean;
3
data: any;
4
error: any;
5
type: "data"|"close"|"error"|"init";
6
channel: string;
7
pattern?: string; // Only in case of pattern subscribe
8
}
Copied!

Example

1
RedisProvider.GetConnection().getSubscriber(true, "room-*").subscribe(
2
message=>{
3
// handle message
4
},
5
err=>{
6
// handle error
7
});
Copied!

Decorators

Another way to subscribe channel\pattern messages is using the following decorators

Subscribe to channel

1
OnRedisMessage<ResponseType = any>(channel: string,...middlewares: Array<(msg: PubSubMessage<ResponseType>) => TValid>);
Copied!
Or
1
OnRedisMessage<ResponseType = any>(channel: string,connectionName?: string,...middlewares: Array<(msg: PubSubMessage<ResponseType>) => TValid>);
Copied!
Example:
1
@OnRedisMessage('decoratorTest', (msg) => {
2
return msg.data > 10; // This middleware will act as filter,
3
// only messagea with data greater than 10 will continue to the next method
4
5
})
6
public static channelListener(data) {
7
this.decoratorTestChannel = data
8
}
Copied!
Subscribe to pattern
1
OnRedisPMessage<ResponseType = any>(channel: string,...middlewares: Array<(msg: PubSubMessage<ResponseType>) => TValid>);
Copied!
Or
1
OnRedisPMessage<ResponseType = any>(channel: string,connectionName?: string,...middlewares: Array<(msg: PubSubMessage<ResponseType>) => TValid>);
Copied!
Example:
1
@OnRedisPMessage('decoratorTestPattern-*', null, (msg:PubSubMessage<number>) => {
2
return msg.data > 10; // This middleware will act as filter,
3
// only messagea with data greater than 10 will continue to the next method
4
})
5
public static patternListener(msg) {
6
this.decoratorTestPattern = msg;
7
}
Copied!
Last modified 2yr ago