本地延迟队列
本地延迟队列
DelayQueue是无界的
特殊注意: 放入DelayQueue队列中的数据必须实现Delay接口,可以通过指定方法获取到是否到执行时间及比较运算逻辑
1.定义本地延迟队列
@Slf4j
@Component
public class NotificationHisRetryQueue {
private DelayQueue<NotificationResult> queue;
@PostConstruct
public void init() {
queue = new DelayQueue<>();
}
public void push(NotificationResult data) {
queue.offer(data);
}
public BlockingQueue<NotificationResult> getQueue() {
return queue;
}
}
2.NotificationResult实现接口Delayed
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
class NotificationResult implements Delayed{
Long runAt;
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(this.runAt - System.currentTimeMillis(),TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
NotificationResult object = (NotificationResult) o;
return this.runAt.compareTo(object.runAt);
}
}
3. 队列里生产数据
// 按照默认延迟30s的数据进行生产
// 只有30s到期的数据才会被取出
public void pushLocalRetryQueue(NotificationResult notificationResult){
log.info("通知历史{}入mq失败,进入本地重试队列,延迟30秒后进行重试",notificationResult);
notificationResult.setRunAt(System.currentTimeMillis() + 1000 * 30);
notificationHisRetryQueue.push(notificationResult);
}
4.队列消费数据
NotificationResult result = notificationHisRetryQueue.getQueue().take();
原创:做时间的朋友