search
HomeDatabaseRedisHow to use redis publish and subscribe method to implement a simple messaging system

I. Basic usage

1. Configuration

We use SpringBoot 2.2.1.RELEASE to build the project environment, directly in pom.xmlAdd redis dependency in

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

If our redis is the default configuration, you do not need to add any additional configuration; you can also directly configure it in application.yml, as follows

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password:

2. Usage posture

Publish/subscribe of redis mainly uses two commandspublish/subscribe; It is relatively simple to use the publish and subscribe mode in SpringBoot, and it is very convenient with the help of RedisTemplate Implementation

a. Message publishing

@Service
public class PubSubBean {
    @Autowired
    private StringRedisTemplate redisTemplate;

    public void publish(String key, String value) {
        redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                redisConnection.publish(key.getBytes(), value.getBytes());
                return null;
            }
        });
    }
}

b. Subscription message

Message subscription here, it should be noted that we use org.springframework.data.redis.connection. MessageListener to implement consumption logic

public void subscribe(MessageListener messageListener, String key) {
    redisTemplate.execute(new RedisCallback<Object>() {
        @Override
        public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
            redisConnection.subscribe(messageListener, key.getBytes());
            return null;
        }
    });
}

c. Test case

Write a simple test case to verify the above publish and subscribe, and understand thisMessageListenerUsage posture; we create a simple WEB project and provide two rest interfaces

@RestController
@RequestMapping(path = "rest")
public class DemoRest {
    @Autowired
    private PubSubBean pubSubBean;

    // 发布消息
    @GetMapping(path = "pub")
    public String pubTest(String key, String value) {
        pubSubBean.publish(key, value);
        return "over";
    }

    // 新增消费者
    @GetMapping(path = "sub")
    public String subscribe(String key, String uuid) {
        pubSubBean.subscribe(new MessageListener() {
            @Override
            public void onMessage(Message message, byte[] bytes) {
                System.out.println(uuid + " ==> msg:" + message);
            }
        }, key);
        return "over";
    }
}

We first create two consumers, and then when sending messages, both are received; then add a new consumer Or, when sending a message, all three can receive it

3. Instructions for use and application scenarios

Redis's publish and subscribe is only suitable for relatively simple scenarios. From the above instructions, it is also It can be seen that it is a simple publish and subscribe model, supporting 1 to N, and the messages sent can only be obtained by online consumers (as for those who are not online, it can only be said to be a pity) and for redis , after the message is pushed out, it will be over. As for whether consumers can consume normally, we don’t care.

Emphasis:

  • Only online consumers can receive it To the message

  • Consumers can only get a message once

The next question comes, under what circumstances can it be done? What about publish and subscribe using redis?

Memory-based cache invalidation

Using reids memory for secondary cache can be said to be a relatively common way. With the help of memory-based cache, it can effectively improve System load, but the problem is also obvious. Invalidation of cached data in memory is a problem, especially when an application is deployed on multiple servers. If I want to invalidate a certain memory cache of all servers at the same time, using redis publish/subscribe is one A better choice

SpringCloud Config configuration refresh

Friends who use SpringCloud Config as the configuration center may often encounter this problem. Dynamic refresh after configuration modification is a Problem (of course, the official support is to synchronize through the bus through mq, and you can also force flash through spring boot admin)

With the help of redis publish/subscribe, it is also a good alternative to achieve dynamic refresh of configuration (discussed later) A specific implementation demo, if you are interested, please continue to follow Yihuihui Blog)

redis key invalid subscription

When we use redis for caching, we usually Set an expiration time, redis provides an expiration event, of course it is not enabled by default; we can also subscribe to the cache invalidation event through subscribe

Modify the configuration and enable the key invalidation event

notify-keyspace-events Ex

After restarting redis, subscribe to the invalid event

subscribe __keyevent@0__:expired

The above is the detailed content of How to use redis publish and subscribe method to implement a simple messaging system. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Redis: Beyond SQL - The NoSQL PerspectiveRedis: Beyond SQL - The NoSQL PerspectiveMay 08, 2025 am 12:25 AM

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

Redis: A Comparison to Traditional Database ServersRedis: A Comparison to Traditional Database ServersMay 07, 2025 am 12:09 AM

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

Redis: Introduction to a Powerful In-Memory Data StoreRedis: Introduction to a Powerful In-Memory Data StoreMay 06, 2025 am 12:08 AM

Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

Is Redis Primarily a Database?Is Redis Primarily a Database?May 05, 2025 am 12:07 AM

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redis: Database, Server, or Something Else?Redis: Database, Server, or Something Else?May 04, 2025 am 12:08 AM

Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

Redis: Unveiling Its Purpose and Key ApplicationsRedis: Unveiling Its Purpose and Key ApplicationsMay 03, 2025 am 12:11 AM

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

Redis: A Guide to Key-Value Data StoresRedis: A Guide to Key-Value Data StoresMay 02, 2025 am 12:10 AM

Redis is an open source memory data structure storage used as a database, cache and message broker, suitable for scenarios where fast response and high concurrency are required. 1.Redis uses memory to store data and provides microsecond read and write speed. 2. It supports a variety of data structures, such as strings, lists, collections, etc. 3. Redis realizes data persistence through RDB and AOF mechanisms. 4. Use single-threaded model and multiplexing technology to handle requests efficiently. 5. Performance optimization strategies include LRU algorithm and cluster mode.

Redis: Caching, Session Management, and MoreRedis: Caching, Session Management, and MoreMay 01, 2025 am 12:03 AM

Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.