2017-12-27 198 views
0

假設有一個ActiveMq實例,並且有100個客戶端正在監聽主題。 當在主題中發佈新消息時,是否可以限制接收它的訂閱者數量(僅示例10)?限制在ActiveMq主題中發送消息的訂戶的最大數量

如果現在有其他消息傳遞組件能夠做到這一點,或者存在解決方案/合併最佳實踐?

回答

0

開箱即不可配置,但您可以創建一個插件來做這樣的事情非常簡單。

一個插件,攔截addConsumer,並且如果已經有太多訂閱者會拋出一些SecurityException。它也可以從activemq.xml config進行配置。

請注意,這是一個快速和骯髒的例子,你可能需要加強它。

MaxSubscribersPlugin.java

import org.apache.activemq.broker.BrokerPluginSupport; 
import org.apache.activemq.broker.ConnectionContext; 
import org.apache.activemq.broker.region.Destination; 
import org.apache.activemq.broker.region.Subscription; 
import org.apache.activemq.command.ActiveMQDestination; 
import org.apache.activemq.command.ConsumerInfo; 

import java.util.Map; 

public class MaxSubscribersPlugin extends BrokerPluginSupport{ 

    private int maxSubscribers = 1000; 

    @Override 
    public Subscription addConsumer(ConnectionContext ctx, ConsumerInfo info) throws Exception { 
     ActiveMQDestination dest = info.getDestination(); 
     if (dest.isTopic() && !dest.getQualifiedName().contains("Advisory")) { // TODO better way to filter out Advisories 
      Map<ActiveMQDestination, Destination> destinations = ctx.getBroker().getBrokerService() 
                    .getAdminView().getBroker().getDestinationMap(); 
      Destination activeTopic = destinations.get(info.getDestination()); 
      if(activeTopic != null && activeTopic.getConsumers().size() >= getMaxSubscribers()) { 

       throw new SecurityException("Too many active subscribers on topic " 
         + info.getDestination().getPhysicalName() 
         + ". Max is " + getMaxSubscribers()); 
      } 
     } 

     return super.addConsumer(ctx, info); 
    } 

    public int getMaxSubscribers() { 
     return maxSubscribers; 
    } 

    public void setMaxSubscribers(int maxSubscribers) { 
     this.maxSubscribers = maxSubscribers; 
    } 

} 

裝箱打包在一個.jar並把它在ActiveMQ中的lib文件夾。然後你可以配置它。

<plugins> 
      <bean xmlns="http://www.springframework.org/schema/beans" id="throttler" 
       class="my.package.MaxSubscribersPlugin"> 
      <property name="maxSubscribers" value="10"/> 
     </bean> 
    </plugins> 

然後,如果有太多的消費者建立聯繫 - 他們會得到一個異常:javax.jms.JMSSecurityException: Too many active subscribers on topic topicX. Max is 10

會有在ActiveMQ的日誌條目記錄以及:

WARN | Security Error occurred on connection to: tcp://127.0.0.1:52335, Too many active subscribers on topic topicX. Max is 10

相關問題