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

穿精又带淫゛_ 提交于 2019-12-05 07:01:16

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);
                }
            }


        }
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!