Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use redis to realize message publish and subscribe in php

Shulou Source: shulou.com Published: 2022-06-02 09:36:25 09月25日 Update

This article is about how to use redis to achieve news release and subscription in php. I think it is very practical, so I share it with you. I hope you can get something after reading this article.

Basic introduction

Pub/Sub function (means Publish, Subscribe) that is publish and subscribe function

Pub/Sub is a widely used communication model in event-based systems, which uses events as the basic communication mechanism to provide a loosely coupled interaction mode required by large-scale systems: subscribers (such as clients) express an event or a class of events that they are interested in receiving in the form of event subscriptions; publishers (such as servers) can notify relevant subscribers of events of interest to subscribers at any time.

Message publishers, that is, publish clients, do not need exclusive links. You can use the same redis-client link for other operations while publish messages (for example, INCR, etc.)

The message subscriber, the subscribe client, requires an exclusive link, that is, during the subscribe, the redis-client cannot be interspersed with other operations, and the client waits for a message from the "publish side" in a blocking manner; this is understandable, so the subscribe side needs to use a separate link, even in additional threads.

When using bank cards for consumption, banks often notify users of the transaction through Wechat, text messages or e-mail, which is a publish and subscription model, where the release is the release of transaction information, and subscriptions are various channels. This is very common in practical work, and Redis supports such a pattern.

The publish and subscribe model first requires a message source, that is, to publish a message, such as a bank notification in the example. First of all, the bank's accounting system, received the transaction order, successful bookkeeping, it will send the message, at this time, subscribers can receive the message for processing, the observer pattern is a typical application of this pattern.

Terminal implementation

Subscribe, channel is' chat'

Publish a message

Code implementation

Subscribe.php

Tags: Subscriptions methods messages patterns functions events methods subscribers channels commands systems banks links different information parameters customers clients that is transactions Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS vpn MySQL Shulou Technology Shulou Tech Info