国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
1. Function Overview
2. Event types
3. Configuration
三、案例
代碼
新增和修改都是set指令
刪除
過期
Home Database Redis How SpringBoot monitors redis Key change events

How SpringBoot monitors redis Key change events

May 26, 2023 pm 01:55 PM
redis springboot key

1. Function Overview

Key space notification allows the client to receive events that have changed the Redis key in some way by subscribing to the channel or mode.

All commands that modify key keys.

All keys that receive the LPUSH key value [value …] command.

All expired keys in the db database.

Events are distributed through the subscription and publishing functions (pub/sub) of Redis, so all clients that support the subscription and publishing functions can directly use the key without making any modifications. Space notification function.

Because the current subscription and publishing functions of Redis adopt a fire and forget strategy, if your program requires reliable notification of events, then the current key space notification may Not suitable for you: When a client subscribed to events goes offline, it loses all events that were distributed to it during the disconnection.

In the future, more reliable event distribution will be supported. This support may be achieved by making the subscription and publishing functions themselves more reliable, or by subscribing and publishing messages in Lua scripts. Publish to listen to achieve operations like pushing events to a list.

2. Event types

For each operation that modifies the database, keyspace notifications will send two different types of events.

For example, when executing the DEL key [key …] command on the key mykey of database 0, the system will distribute two message, which is equivalent to executing the following two PUBLISH channel message commands:

PUBLISH __keyspace@0__:mykey del
PUBLISH __keyevent@0__:del mykey

Subscribing to the first channel __keyspace@0__:mykey can receive events for all modified keys mykey in database No. 0, Subscribing to the second channel __keyevent@0__:del can receive all keys that execute the del command in database No. 0.

The channel prefixed by keyspace is called key-space notification, and the channel prefixed by keyevent is called key-event notification.

When the del mykey command is executed:

  • Subscribers to the keyspace channel will receive the name of the event that was executed, in this example, del .

  • Subscribers to the key event channel will receive the name of the key for which the event was executed, in this example, mykey .

3. Configuration

Because turning on the key space notification function requires some CPU, so in the default configuration, this function is turned off.

You can turn on or off the keyspace notification function by modifying the redis.conf file or directly using the CONFIG SET command:

When the parameter of the notify-keyspace-events option is an empty string, Function is turned off.

On the other hand, when the parameter is not an empty string, the function is turned on.

The parameters of notify-keyspace-events can be any combination of the following characters, which specifies which types of notifications the server should send:

How SpringBoot monitors redis Key change events

Input parameters There must be at least one K or E in it, otherwise, no matter what the other parameters are, no notification will be distributed.

For example, if you only want to subscribe to notifications related to lists in the keyspace, then the parameter should be set to Kl, and so on.

Set the parameter to a string "AKE" means sending all types of notifications.

Whenever a key is deleted due to expiration, an expired notification is generated.

Generate an evicted notification whenever a key is deleted to reclaim memory due to the maxmemory policy.

All commands will only generate notifications after the key has actually been changed.

For example, when SREM key member [member …h(huán)ellip;] attempts to delete an element that does not exist in the collection, the deletion operation will fail because there is no real change to the key, so this Notifications will not be sent for the operation.

If you have any questions about the notification generated by the command, it is best to use the following command to verify it yourself:

Redis uses the following two methods to delete expired keys:

When a key is accessed, the program will check the key. If the key has expired, the key will be deleted.

The underlying system will progressively find and delete expired keys in the background to process keys that have expired but will not be accessed.
When an expired key is discovered by either of the above two programs and the key is deleted from the database, Redis will generate an expired notification.

Redis does not guarantee that a key whose lifetime (TTL) becomes 0 will be deleted immediately: if the program does not access this expired key, or if there are too many keys with lifetime, then the key The lifetime becomes 0, and there may be a significant time interval between when the key is actually deleted.

因此, Redis 產(chǎn)生expired通知的時間為過期鍵被刪除的時候, 而不是鍵的生存時間變?yōu)?0 的時候。

三、案例

按上文內(nèi)容,我們先將redis的鍵空間通知開啟,我們開啟所有的通知,在可以端中測試后沒問題再到代碼中測試。

連接到redis 輸入一下命令

How SpringBoot monitors redis Key change events

config set notify-keyspace-events KEA

訂閱鍵空間和鍵事件的主題

How SpringBoot monitors redis Key change events

psubscribe '__key*__:*'#對所有庫鍵空間通知
 
psubscribe '__keyspace@2__:*' #是對db2數(shù)據(jù)庫鍵空間通知
 
psubscribe '__keyspace@2__:order*' #是對db2數(shù)據(jù)庫,key前綴為order所有鍵的鍵空間通知

創(chuàng)建一個 key :name valus:zhangsan

set name wsl

觀察訂閱的窗口 會受到兩個消息,第一個是:鍵空間 第二個是鍵事件,鍵空間是內(nèi)容是操作指令,主題中包含有key,鍵事件主題中包含了指令,內(nèi)容是key。

How SpringBoot monitors redis Key change events

到這里說明已經(jīng)開啟了鍵空間通知

代碼

以下代碼采用string類型演示

在配置一下MessageListenerContainer類,將我們寫好的監(jiān)聽類添加到該類中即可,刪除和過期都是需要添加,我這里就一起添加了后面就不做演示。

@Configuration
public class RedisConfig {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Autowired
    private RedisUpdateAndAddListener redisUpdateAndAddListener;
 
    @Autowired
    private RedisDeleteListener redisDeleteListener;
 
    @Autowired
    private RedisExpiredListener redisExpiredListener;
 
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //監(jiān)聽所有的key的set事件
        container.addMessageListener(redisUpdateAndAddListener, redisUpdateAndAddListener.getTopic());
        //監(jiān)聽所有key的刪除事件
        container.addMessageListener(redisDeleteListener,redisDeleteListener.getTopic());
        //監(jiān)聽所有key的過期事件
        container.addMessageListener(redisExpiredListener,redisExpiredListener.getTopic());
        return container;
    }
 
 
}

新增和修改都是set指令

所以監(jiān)聽的主題都一樣,實現(xiàn)MessageListener接口,重寫onMessage這里就是收到消息的處理邏輯

@Component
@Data
public class RedisUpdateAndAddListener implements MessageListener {
	//監(jiān)聽的主題
    private  final PatternTopic topic = new PatternTopic("__keyevent@*__:set");
 
    @Override
    public void onMessage(Message message,byte[] pattern){
        String topic = new String(pattern);
        String msg = new String(message.getBody());
        System.out.println("收到key更新或修改,消息主題是:"+ topic+",消息內(nèi)容是:"+msg);
    }
 
}

在redis中對name這個key進(jìn)行set操作

set name wsl

在控制臺就可以看到name這個key被操作了

How SpringBoot monitors redis Key change events

刪除

跟上面的更新監(jiān)聽一樣,只需要把訂閱主題更改一下即可。同樣需要添加到這個RedisMessageListenerContainer,上面已經(jīng)添加,這里不做演示

@Component
@Data
public class RedisDeleteListener implements MessageListener {
 
    //監(jiān)聽主題
    private  final PatternTopic topic = new PatternTopic("__keyevent@*__:del");
 
    /**
     *
     * @param message 消息
     * @param pattern 主題
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String topic = new String(pattern);
        String msg = new String(message.getBody());
        System.out.println("收到key的刪除,消息主題是:"+ topic+",消息內(nèi)容是:"+msg);
    }
}

在redis輸入命令,del name 在控制臺可以看到已經(jīng)收到消息了。

How SpringBoot monitors redis Key change events

過期

如上面的操作方式一樣

@Data
@Component
public class RedisExpiredListener implements MessageListener {
 
    //監(jiān)聽主題
    private  final PatternTopic topic = new PatternTopic("__keyevent@*__:expired");
 
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String topic = new String(pattern);
        String msg = new String(message.getBody());
        System.out.println("收到key的過期,消息主題是:"+ topic+",消息內(nèi)容是:"+msg);
    }
}

?在redis中寫一個定時刪除的keySETEX age 18 3三秒后就可以控制臺打印了相關(guān)信息

How SpringBoot monitors redis Key change events

The above is the detailed content of How SpringBoot monitors redis Key change events. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
Recommended Laravel's best expansion packs: 2024 essential tools Recommended Laravel's best expansion packs: 2024 essential tools Apr 30, 2025 pm 02:18 PM

The essential Laravel extension packages for 2024 include: 1. LaravelDebugbar, used to monitor and debug code; 2. LaravelTelescope, providing detailed application monitoring; 3. LaravelHorizon, managing Redis queue tasks. These expansion packs can improve development efficiency and application performance.

Laravel environment construction and basic configuration (Windows/Mac/Linux) Laravel environment construction and basic configuration (Windows/Mac/Linux) Apr 30, 2025 pm 02:27 PM

The steps to build a Laravel environment on different operating systems are as follows: 1.Windows: Use XAMPP to install PHP and Composer, configure environment variables, and install Laravel. 2.Mac: Use Homebrew to install PHP and Composer and install Laravel. 3.Linux: Use Ubuntu to update the system, install PHP and Composer, and install Laravel. The specific commands and paths of each system are different, but the core steps are consistent to ensure the smooth construction of the Laravel development environment.

Redis: A Comparison to Traditional Database Servers Redis: A Comparison to Traditional Database Servers May 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.

How to limit user resources in Linux? How to configure ulimit? How to limit user resources in Linux? How to configure ulimit? May 29, 2025 pm 11:09 PM

Linux system restricts user resources through the ulimit command to prevent excessive use of resources. 1.ulimit is a built-in shell command that can limit the number of file descriptors (-n), memory size (-v), thread count (-u), etc., which are divided into soft limit (current effective value) and hard limit (maximum upper limit). 2. Use the ulimit command directly for temporary modification, such as ulimit-n2048, but it is only valid for the current session. 3. For permanent effect, you need to modify /etc/security/limits.conf and PAM configuration files, and add sessionrequiredpam_limits.so. 4. The systemd service needs to set Lim in the unit file

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: Beyond SQL - The NoSQL Perspective Redis: Beyond SQL - The NoSQL Perspective May 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.

Steps and examples for building a dynamic PHP website with PhpStudy Steps and examples for building a dynamic PHP website with PhpStudy May 16, 2025 pm 07:54 PM

The steps to build a dynamic PHP website using PhpStudy include: 1. Install PhpStudy and start the service; 2. Configure the website root directory and database connection; 3. Write PHP scripts to generate dynamic content; 4. Debug and optimize website performance. Through these steps, you can build a fully functional dynamic PHP website from scratch.

Redis: Unveiling Its Purpose and Key Applications Redis: Unveiling Its Purpose and Key Applications May 03, 2025 am 12:11 AM

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

See all articles