SpringCloud集成Redis失效监听器

通过配置Redis服务器,开启其失效通知事件

主要设置方式:在redis.conf中设置

notify-keyspace-events Ex

这样在redis键值对儿失效时,就可以在服务中接收过期通知

springcloud配置:

1、添加依赖


	org.springframework.boot
	spring-boot-starter-data-redis

2、创建监听器类,监听器配置类

package com.icare.bracelet.sso.consume;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.lang.Nullable;

/**
 * 
 *    author  : Tianhaibo
 *    email   : [email protected]
 *    time    : 2018/9/18   15:34
 *    desc    : redis过期消息监听类
 *    version : v1.0
 * 
*/ @Slf4j @Configuration @ConditionalOnProperty(value = "listener.redis.expire") public class RedisExpiredListener implements MessageListener { @Override public void onMessage(Message message, @Nullable byte[] pattern) { log.info("接收过期消息--->key={},val={}",new String(message.getChannel()),new String(message.getBody())); } }
package com.icare.bracelet.sso.consume;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import java.util.concurrent.Executor;

/**
 * 
 *    author  : Tianhaibo
 *    email   : [email protected]
 *    time    : 2018/9/18   15:38
 *    desc    : redis监听配置类
 *    version : v1.0
 * 
*/ @Slf4j @Configuration @ConditionalOnBean(RedisExpiredListener.class) public class RedisListenerConfig { @Autowired private StringRedisTemplate redisTemplate; @Value("${listener.redis.expire}") private String topic; @Autowired @Qualifier("initExecutor") private Executor executor; @Bean public RedisMessageListenerContainer initRedisMessageListenerContainer(RedisExpiredListener redisExpiredListener){ RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(redisTemplate.getConnectionFactory()); container.setTaskExecutor(executor); container.addMessageListener(redisExpiredListener,new ChannelTopic(topic)); log.info("Initializing RedisListener success!"); return container; } }

上面的类注解中listener.redis.expire是在springcloud中配置的开关,配置:

#配置redis失效消费主体(redis.config.db是redis配置中的db,可选0-15)
listener.redis.expire=__keyevent@${redis.config.db}__:expired

其中RedisListenerConfig类中的Executor 是异步线程执行器,主要用于并发时,可以异步队列执行,提高效率;
这个是需要自己按需进行配置的

/**
     * 自定义异步线程池
     * @return
     */
    @Bean
    public Executor initExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(10);
        //核心线程数
        threadPoolTaskExecutor.setCorePoolSize(3);
        //任务队列大小
        threadPoolTaskExecutor.setQueueCapacity(25);
        //线程空闲存活最大时间
        threadPoolTaskExecutor.setKeepAliveSeconds(300);
        //设置拒绝服务策略(当前无线程可以用的情况下),CallerRunsPolicy标识由调用者所在线程来处理
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

监听配置中有个属性topic很重要,这个是决定监听器匹配监听哪些类型的redis事件,在redis配置中有明确说明

############################# EVENT NOTIFICATION ##############################

# Redis can notify Pub/Sub clients about events happening in the key space.
# This feature is documented at http://redis.io/topics/notifications
#
# For instance if keyspace events notification is enabled, and a client
# performs a DEL operation on key "foo" stored in the Database 0, two
# messages will be published via Pub/Sub:
#
# PUBLISH __keyspace@0__:foo del
# PUBLISH __keyevent@0__:del foo
#
# It is possible to select the events that Redis will notify among a set
# of classes. Every class is identified by a single character:
#
#  K     Keyspace events, published with __keyspace@__ prefix.
#  E     Keyevent events, published with __keyevent@__ prefix.
#  g     Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ...
#  $     String commands
#  l     List commands
#  s     Set commands
#  h     Hash commands
#  z     Sorted set commands
#  x     Expired events (events generated every time a key expires)
#  e     Evicted events (events generated when a key is evicted for maxmemory)
#  A     Alias for g$lshzxe, so that the "AKE" string means all the events.
#
#  The "notify-keyspace-events" takes as argument a string that is composed
#  of zero or multiple characters. The empty string means that notifications
#  are disabled.
#
#  Example: to enable list and generic events, from the point of view of the
#           event name, use:
#
#  notify-keyspace-events Elg
#
#  Example 2: to get the stream of the expired keys subscribing to channel
#             name __keyevent@0__:expired use:
#
#  notify-keyspace-events Ex
#
#  By default all notifications are disabled because most users don't need
#  this feature and the feature has some overhead. Note that if you don't
#  specify at least one of K or E, no events will be delivered.
notify-keyspace-events Ex

这些就可以满足消费失效时间消息了,但是有一点需要注意,消费到的消息中Message中的body中只有失效消息的key,,因此在业务使用时需要注意,要将需要的信息包含在key中
这种形式的失效监听,会有一定的时间延迟,可靠性要去继续连接redis官方文档了

你可能感兴趣的:(Java)