[TOC]

Redis is often used for caching operations, but redis does more than that. Today we will look at the key failure event of Redis

Redis installation

  • For easy installation. We install Redis directly using Docker. I won’t say much about Docker here. Just post the code and script it yourself

Docker pull

Docker pull redis: 3.2

Start the

docker run -p 6379:6379 -v /opt/soft/docker/redis/redis.conf:/etc/redis/redis.conf -v /opt/soft/docker/redis/data:/data --name=myredis --restart=always -d redis:3.2 redis-server /etc/redis/redis yesCopy the code
  • For security, we still set the password, and change the script password to your own password

  • The above/opt/soft/docker/redis/data that we only need to create an empty folder, the us is to map the redis log out convenient location problem.

  • The redis. Conf file can be downloaded from the official website. Docker installed Redis has no configuration file by default. Or I could just copy what I have here.

# Note on units: when memory size is needed, it is possible to specifiy # it in the usual form of 1k 5GB 4M and so forth: # # 1k => 1000 bytes # 1kb => 1024 bytes # 1m => 1000000 bytes # 1mb => 1024*1024 bytes # 1g => 1000000000 bytes # 1gb => insensitive (insensitive) 1024*1024*1024 bytes # # units are case insensitive so 1GB 1GB 1GB are all the same. /var/run/redis.pid daemonize no # When Redis is running as a daemon, the pid is written to a pidfile. Pid /var/run/ Redis. Pid = pidfile /var/run/ Redis. Pid = pidfile /var/run/ Redis. Redis does not listen on TCP connections port 6379 # bind host address # You can bind a single interface, if there is no bind, All interfaces will listen for incoming connections # bind 127.0.0.1 # Specify the path for the Unix socket that will be used to listen for # incoming connections. There is no default, so Redis will not listen # on a unix socket when not specified. # # unixsocket /tmp/redis.sock # unixsocketperm 755 # Timeout 0 # Specifies the logging level. Redis supports four levels: Debug, verbose, notice, warning, The default is verbose # debug (a lot of information, useful for development/testing) but not a mess like the debug level) # notice (moderately verbose, what you want in production probably) # warning (only very important / critical messages are logged) loglevel verbose # Log mode, the default is standard output. If redis is configured to run in daemon mode, and this is configured as standard output, /dev/null logfile stdout # To enable logging To the system Logger, just set 'syslog-enabled' To yes, # and optionally update the other syslog parameters to suit your needs. # syslog-enabled no # Specify the syslog identity. # syslog-ident redis # Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7. # syslog-facility Local0 # Set the number of databases, default is 0, Can use the select < dbid > command specified in the connection database id # dbid from 0 to the number of 'databases - 1 the databases of 16 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # SNAPSHOTTING # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # specified in how long, how many times the update operation, the synchronization of data to a data file, can be multiple conditions with # Save the DB on disk: # # save <seconds> <changes> # # Will save the DB if both the given number of seconds and the given # number of write Operations against the DB occurred. # # Data will be synchronized if the following conditions are met: 1 change within 900 seconds # 10 change within 300 seconds # 10000 change within 60 seconds # Note: Save 900 1 save 300 10 save 60 10000 # specify whether to compress data when storing to local database. Default: yes RDB dbfilename dump. RDB dbfilename dump. RDB # # Also the Append Only File will be created inside this directory. Cannot specify filename dir. / notify - keyspace - events Ex # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # the REPLICATION # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #Copy the code

Redis configuration

  • I’ve already configured this up here. You can download the default configuration from the official website. I added a configuration abovenotify-keyspace-events Ex. Ex is explained in the following table
attribute instructions
K Keyspace notifications, all notifications prefixed with keyspace@, chasing key
E Key event notification, all notifications prefixed with keyspace@, chasing event
g DEL, EXPIRE, RENAME, and other types of generic command notification
$ String command notification
l List command notification
s Collection command notification
h Hash command notification
z Zset command notification
x Expiration event notification, which is triggered whenever a key expires
e The expulsion event is triggered whenever there is a key because the MaxMemory policy is clear
A G $lshzxe floorboard

Command to monitor

  • After the above configuration, we open the Redis client

docker exec -it myredis redis-cli

Copy the code
  • Myredis is the alias of the container above which Redis is installed. This can be set up by the reader
  • Since the password is set, we need to verify the password after connecting

auth password

Copy the code
  • Then register the listener

PSUBSCRIBE __keyevent@*__:expired

  • Expired is our registration type, and the * after the @ indicates DB. Here we listen for key expiration events for all databases.

The problem

  • Let’s say we want to listen for DB0’s key deletion event. We can register like thisPSUBSCRIBE __keyevent@0__:del

  • 127.0.0.1:6379 If there is no number after it, the default db0 is used.

  • Switch to DB1 and check that hello is not found. And 6379 is followed by the database index value. At this point, add hello to DB1 and delete it. See if another listener listening to DB0 responds

  • Obviously, we didn’t have any notice. Now let’s delete Hello in DB0. Look at the effect of the listener
  • The deletion in DB0 at this time also does not monitor the information. I don’t know why. Still hope to give directions

Procedures to monitor

  • The SpringBoot program adds dependencies

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

Copy the code


@Configuration
public class RedisConfig {
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory) {
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
        returnredisMessageListenerContainer; }}Copy the code
  • This is just to demonstrate listening for expired events. So redisConfig doesn’t add much configuration here.
Spring: redis: host: 39.102.60.114 Port: 6379 database: 0 password: password timeout: 1000sCopy the code

Concrete listener class



@Slf4j
@Component
public class RedisKeyExpireListener extends KeyExpirationEventMessageListener {

    public RedisKeyExpireListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        log.info("Received message: {}, {}",message,newString(pattern)); }}Copy the code

The effect

conclusion

  • Listening for key expiration events is not actually used very much. Because redis is mostly for caching. Caching was always going to be dispensable. So there’s not much point in eavesdropping. But it can also be used in a number of scenarios.
  • An order is automatically cancelled without payment after 30 minutes
  • System periodic reminder function