Java中Redis到期事件通知(key过期,触发事件)

编程

1.  在redis.conf 中修改   notify-keyspace-events Ex 这一行的注释打开

2. 

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.redis.connection.RedisConnectionFactory;

import org.springframework.data.redis.listener.RedisMessageListenerContainer;

@Configuration

public class RedisListenerConfig {

@Bean

RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {

RedisMessageListenerContainer container = new RedisMessageListenerContainer();

container.setConnectionFactory(connectionFactory);

//container.addMessageListener(new RedisExpiredListener(), new PatternTopic("__keyevent@0__:expired"));

return container;

}

}

 

3.

import com.mayikt.api.service.user.EduTempMemberService;

import com.mayikt.api.service.user.UserService;

import com.mayikt.entity.user.EduTempMember;

import org.apache.commons.lang3.StringUtils;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.connection.Message;

import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;

import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import org.springframework.stereotype.Component;

@Component

public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

@Autowired

private EduTempMemberService eduTempMemberService;

@Autowired

private UserService userService;

private final static Logger logger = LoggerFactory.getLogger(RedisKeyExpirationListener.class);

/* @Autowired

private RedisClient redisClient;*/

public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {

super(listenerContainer);

}

private final static String MAYIKT_REDIS_KEY="mayikt_member";

@Override

public void onMessage(Message message, byte[] pattern) {

// 用户做自己的业务处理即可,注意message.toString()可以获取失效的key

String expiredKey = message.toString();

Integer userId=null;

if(expiredKey.startsWith(MAYIKT_REDIS_KEY)){

//获取token 使用token 进行修改用户会员

if (!StringUtils.isBlank(expiredKey.substring(14))){

String token=expiredKey.substring(14);

EduTempMember eduTempMember = eduTempMemberService.queryEduTempMemberByToken(token);

System.out.println("eduTempMember--"+eduTempMember);

if (eduTempMember!=null){

userId=eduTempMember.getUserId();

userService.updateUserIsVip(userId);

}

}

}

}

}

 

以上是 Java中Redis到期事件通知(key过期,触发事件) 的全部内容, 来源链接: utcz.com/z/511043.html

回到顶部