通过 JNDI 使用 ActiveMQ

问题描述 投票:0回答:2

我正在尝试使用 JNDI 创建与 ActiveMQ 的简单连接。

我有:

  1. 队列名为
    example.A
  2. 根据涉及 JNDI 的 ActiveMQ 文档,如果我想通过 JNDI 使用 ConectionFactories 和队列(主题),我必须将
    jndi.properties
    文件放在我的类路径上。据我了解,ActiveMQ 类路径默认是
    %activemq%/conf
    目录。我没有改变它。所以我的队列有这个属性:
    queue.MyQueue = example.A
    
  3. 我为ActiveMQ创建了java客户端类,它使用JNDI,如下所示:
    Properties jndiParameters = new Properties() ;
    jndiParameters.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
    jndiParameters.put(Context.PROVIDER_URL, "tcp://localhost:61616");
    Context context = new InitialContext(jndiParameters);
    ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("ConnectionFactory");
    Queue queue = (Queue) context.lookup("MyQueue");
    

但它找不到我的队列。它抛出异常:

javax.naming.NameNotFoundException: MyQueue

我的错误在哪里?

java jndi activemq-classic
2个回答
6
投票

问题在于您显式创建属性并将它们传递到 InitialContext 构造函数中。这意味着类路径上的 jndi.properties 将不会被读取。

你的代码应该是这样的:

Context context = new InitialContext();
ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("ConnectionFactory");
Queue queue = (Queue) context.lookup("MyQueue");

1
投票

您可以设置静态属性以及从文件中检索它们,如下所示:

    InputStream is = getClass().getResourceAsStream("/my.jndi.properties");
    Properties jndiParameters = new Properties();
    jndiParameters.load(is);
    jndiParameters.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
    jndiParameters.put(Context.PROVIDER_URL, "tcp://localhost:61616");
    Context ctx =  new InitialContext(jndiParameters);
...

只要您在加载资源后设置静态属性,这就可以工作。例如,如果您从其他地方加载提供程序 URL,这会很有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.