系统的看完各个设计模式,和开闭原则,实际中其实往往想不到如何使用
比如业务场景,通过redis来模拟延迟消息处理
还是采用传统思维模式
写入消息
// 离线列表 延迟一分钟 redisOperationService.zaddWithPrefix(BusinessRedisKeyDefinition.SESSION_STATE_OFFLINE_QUEUE.get(privateProviderId), System.currentTimeMillis() + 60000, key, expirationDate);
定时任务扫描处理
Date currentDate = new Date(); // 每次处理100条 final Set<Tuple> tuples = redisOperationService.zrangeByScoreWithScores(queueKey, 0, Long.valueOf(currentDate.getTime()).doubleValue(), 0, 100);
但是为什么不统一封装设计呢
public interface MessageInvoker { void invoke(String message); }
public class RedisJobScheduler { MessageInvoker messageInvoker; private RedisOperationService redisOperationService; // 扫描频率 private Integer interval = 1000; // 默认处理行数 private Integer batchProcessNumber = 10; // 任务不活跃多久自动过期 private int expirationDate = 60 * 60 * 12 * 2 * 2; private String taskName; public void addJob(String message, Integer delayMillis) { redisOperationService.zaddWithPrefix(taskName, System.currentTimeMillis() + delayMillis, message, expirationDate); } public void startJob() { new Thread(() -> { while (true) { try { Thread.sleep(interval); // 1. 获取消息 Set<String> messageName = redisOperationService.zrangeByScoreWithPrefix(taskName, 0, Long.valueOf(new Date().getTime()).doubleValue(), 0, batchProcessNumber); for (String message : messageName) { // 3. 处理任务 messageInvoker.invoke(message); // 4. 删除任务 redisOperationService.zremWithPrefix(taskName, message); } } catch (InterruptedException e) { throw new RuntimeException(e); } } }); } }
这里startjob还可以采用动态新建的方式
https://www.cnblogs.com/LQBlog/p/17188613.html
标签:String,之美,private,反思,new,message,设计模式,redisOperationService,taskName From: https://www.cnblogs.com/LQBlog/p/18021697