一下应用 redis key 过期事件的过期通知 来实现 监听
1.监听监听器
代码1
package mms.shop.biz.mq.listener;
import java.util.HashMap;
import mms.shop.biz.mq.handler.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
public class RedisExpiredListener implements MessageListener {
/**
* 客户端监听订阅的topic,当有消息的时候,会触发该方法; 并不能得到value, 只能得到key。 姑且理解为:
* redis服务在key失效时(或失效后)通知到java服务某个key失效了,
* 那么在java中不可能得到这个redis-key对应的redis-value。
*/
@Autowired
private HashMap<Integer, A> ARouter;
@Override
public void onMessage(Message message, byte[] bytes) {
String expiredKey = message.toString();
// TASK:CODE:VALUE结构
String[] split = expiredKey.split(":");
if (split.length < 2 || !expiredKey.startsWith("TASK:")) {
return;
}
StringBuilder value = new StringBuilder();
for (int i = 2; i < split.length; i++) {
value.append(split[i]);
if (i != split.length - 1) {
value.append(":");
}
}
int code = Integer.parseInt(split[1]);
A handler = ARouter.get(code);
if (handler != null) {
//调用方法
handler.handle(value.toString());
}
}
}
代码2
将代码1中的 ARouter 注入到容器中 redisNotifyHandlerListdfssfsd为容器中现有的实现了 代码3的方法
package mms.shop.biz.config.mq;
import mms.shop.biz.mq.handler.A;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Configuration
public class DelayedMessageQueueConfig {
@Bean
public Map<Integer, A> ARouter(List<A> redisNotifyHandlerListdfssfsd) {
return redisNotifyHandlerListdfssfsd.stream().collect(Collectors.toMap(A::getCode, v -> v));
}
}
代码3
package mms.shop.biz.mq.handler;
public interface A {
public int handle(String value);
public int getCode();
}
代码4
只要是实现了 A 的类 都会被注入到ARouter中 监听后的执行的调用方法
package mms.shop.biz.mq.handler;
public class aimpl implements A {
@Override
public int handle(String value) {
return 0;
}
@Override
public int getCode() {
//如果我需要调用到这个 aimpl 方法 那只需要 在设置0即可
return 0;
}
}
代码1.1 将 aimpl 放入 容器中 供代码2使用 也就是 redisNotifyHandlerListdfssfsd 的值
package mms.shop.biz.config.mq;
import mms.shop.biz.mq.handler.aimpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AConfig {
@Bean
public aimpl aimpl() {
return new aimpl();
}
}
代码5
放入缓存的工具类
package mms