java - 如何防止 ActiveMQ 优先级队列上的低优先级消息被饿死?

标签 java queue message-queue activemq priority-queue

我正在开发一个需要实现优先队列的系统。我们有不同优先级的消息,我们需要根据优先级处理消息。目前,出于多种原因,我们希望使用 ActiveMQ 作为我们的队列技术,其中之一就是支持优先级队列。

对于 ActiveMQ 中的优先队列,处理饥饿的最佳方法是什么?具体来说,我们需要确保即使高优先级的消息继续涌入队列,即使是低优先级的消息最终也能得到处理。 ActiveMQ 有内置的东西吗?或者我们是否需要构建自己的东西来随着消息的老化提高优先级?

最佳答案

一个基本的方法是在消息变老时提高优先级

这样一小时前的低优先级消息比新的高优先级消息具有更高的优先级

public class Message implements Comparable<Message>{

    private final long time;//timestamp from creation (can be altered to insertion in queue) in millis the lower this value the older the message (and more important that it needs to be handled)
    private final int pr;//priority the higher the value the higher the priority

    /**
     * the offset that the priority brings currently set for 3 hours 
     *
     * meaning a message with pr==1 has equal priority than a message with pr==0 from 3 hours ago
     */
    private static final long SHIFT=3*60*60*1000; 

    public Message(int priority){
        this.pr=priority;
        this.time = System.currentTimeMillis();
    }

    //I'm assuming here the priority sorting is done with natural ordering
    public boolean compareTo(Message other){
        long th = this.time-this.pr*SHIFT;
        long ot = other.time-other.pr*SHIFT;
        if(th<ot)return 1;
        if(th>ot)return -1;
        return 0;
    }

}

正如评论中所指出的,但是几个小时前来自低优先级消息的洪水将暂时使新的高优先级消息饿死,并且将这些适本地隔开将需要更复杂的方法


另一种方法是使用多个队列,每个队列一个优先级,每个从低优先级队列中取出的,从高优先级队列中取出几个

最后一种方法仅适用于少量优先级,而我提供的第一种方法可以处理任意数量的优先级

关于java - 如何防止 ActiveMQ 优先级队列上的低优先级消息被饿死?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6393135/

相关文章:

java - 乘以从数据库中选择的大十进制数

apache-kafka - 可靠的fire-n-forget Kafka生产者实现策略

node.js - Heroku 上的 Node JS 消息队列

java - 循环消息/任务队列现有解决方案

java - 控制反转定义

java - 从注解引用参数化类型

java - 如何混合使用 Guice 和 Jersey 注入(inject)?

ios - 如何处理并发执行的大量数据(NSOperationQueue 或 Blocks)

c# - 线程队列进程

java - List不为空但poll方法返回null