使用Redis实现过期监听,类似消息队列,实现消息到期提醒,工单超时等功能 RedisTimeoutConfiguration配置类
@Configuration
public class RedisTimeoutConfiguration {
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Bean
public RedisMessageListenerContainer redisMessageListenerContainer() {
RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
return redisMessageListenerContainer;
}
@Bean
public KeyExpiredListener keyExpiredListener() {
return new KeyExpiredListener(this.redisMessageListenerContainer());
}
}
redisKey过期监听KeyExpiredListener类
@Slf4j
public class KeyExpiredListener extends KeyExpirationEventMessageListener {
@Autowired private RedisCache redisCache;
@Autowired private ISysMessageService sysMessageService;
@Autowired private JdbcTemplate jdbcTemplate;
private String sql = "update sys_message set status=? where id=?";
public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
@Override
public void onMessage(Message message, byte[] pattern) {
String channel = new String(message.getChannel(), StandardCharsets.UTF_8);
String key = new String(message.getBody(), StandardCharsets.UTF_8);
System.out.println(message.toString());
log.info("redis key 过期:pattern={},channel={},key={}", new String(pattern), channel, key);
if (key.contains(TransferConstant.VISIT_RECORD_READY)) {
String[] split = key.split("-");
updateMsgStatus(Long.parseLong(split[1]), 1);
} else if (key.contains(TransferConstant.VISIT_RECORD_WILL)) {
String[] split = key.split("-");
updateMsgStatus(Long.parseLong(split[1]), 0);
SysMessage byId = sysMessageService.getById(Long.parseLong(split[1]));
redisCache.setCacheObject(
TransferConstant.VISIT_RECORD_READY + "-" + byId.getId(),
byId.getId(),
Integer.parseInt(String.valueOf(byId.getVisitId() - System.currentTimeMillis())),
TimeUnit.MILLISECONDS);
}
}
|