Home > Database > Redis > body text

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

WBOY
Release: 2023-05-26 20:52:31
forward
1324 people have browsed it

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>
Copy after login

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:
Copy after login

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;
            }
        });
    }
}
Copy after login

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;
        }
    });
}
Copy after login

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";
    }
}
Copy after login

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
Copy after login

After restarting redis, subscribe to the invalid event

subscribe __keyevent@0__:expired
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template