1.设置redis
/redis-5.0.5/src/redis-cli 6601
config set notify-keyspace-events Ex
这个只是临时的,需要去conf文件redis.conf把notify-keyspace-events Ex释放开
2.配置spring-redis
<bean id="jedisConnectionFactory" p:pool-config-ref="jedisPoolConfig" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.hostName}" />
<property name="port" value="${redis.port}" />
</bean>
<!-- redis.RedisKeyExpiredMessageListener-->
<!-- 配置redis消息订阅 -->
<bean id="messageListener"
class="org.springframework.data.redis.listener.adapter.MessageListenerAdapter">
<constructor-arg>
<!-- 自定义消息处理类 -->
<bean class="redis.RedisKeyExpiredMessageListener" />
</constructor-arg>
</bean>
<bean id="redisContainer"
class="org.springframework.data.redis.listener.RedisMessageListenerContainer">
<property name="connectionFactory" ref="jedisConnectionFactory" />
<property name="messageListeners">
<map>
<entry key-ref="messageListener">
<list>
<!-- 通配符:匹配消息通知类型 -->
<bean class="org.springframework.data.redis.listener.PatternTopic">
<constructor-arg value="__key*__:expired" />
</bean>
</list>
</entry>
</map>
</property>
</bean>
<constructor-arg value="__key*__:expired" />
这个最好手动打一下, __ 这个是两个_ 组成的
3.创建class
package redis;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;
@Component
public class RedisKeyExpiredMessageListener extends MessageListenerAdapter {
/**
* /redis-5.0.5/src/redis-cli 6601
* config set notify-keyspace-events Ex
* 针对redis数据失效事件,进行数据处理
* @param message
* @param pattern
*/
@Override
public void onMessage(Message message, byte[] pattern) {
// 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
String expiredKey = message.toString();
System.out.println(expiredKey);
}
}
亲测可用: