当我们需要动态的根据开始时间或者结束时间来改变某个字段的状态时,我们可以使用
JedisUtil.set(key,subTask.getId(),expireTime.intValue());
根据 springDataRedis来获取key失效的时间,去动态更新字段的状态
1.配置Redis监听配置
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
@Configuration
public class RedisListenerConfig {
@Value("${spring.redis.database}")
private Integer db;
@Bean
public RedisMessageListenerContainer customizeRedisListenerContainer(
RedisConnectionFactory redisConnectionFactory,MessageListener messageListener) {
RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
redisMessageListenerContainer.addMessageListener(messageListener,new PatternTopic("__keyevent@"+db.intValue()+"__:expired"));
return redisMessageListenerContainer;
}
}
2.监听key过期的业务实现类 onMessage中可以写自己的业务代码
import com.lydata.handfulcode.business.train.constant.BusinessConstant;
import com.lydata.handfulcode.business.train.service.ILearnTaskUserRecordService;
import com.lydata.handfulcode.common.redis.JedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Slf4j
@Component
public class KeyExpiredEventMessageListener implements MessageListener {
@Autowired
private ILearnTaskUserRecordService recordService;
@Override
public void onMessage(Message message, byte[] bytes) {
log.info("监听失效的redisKey:{},值是:{}, {}", message.toString(), new String(message.getBody()), new String(bytes));
String expireKey = message.toString();
if (expireKey.startsWith(BusinessConstant.REDIS_KEY_PRE) || expireKey.startsWith(BusinessConstant.REDIS_KEY_START_TIME)) {
String id = expireKey.split(":")[1];
Long subTaskId = Long.valueOf(id);
if (expireKey.startsWith(BusinessConstant.REDIS_KEY_PRE)) {
recordService.updateTaskUserInfoStatus(subTaskId);
} else {
recordService.updateStatusByStartTimeExpire(subTaskId);
}
}
}
}



