我正在尝试使用 JNDI 创建与 ActiveMQ 的简单连接。
我有:
example.A
。jndi.properties
文件放在我的类路径上。据我了解,ActiveMQ 类路径默认是 %activemq%/conf
目录。我没有改变它。所以我的队列有这个属性:
queue.MyQueue = example.A
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
我的错误在哪里?
问题在于您显式创建属性并将它们传递到 InitialContext 构造函数中。这意味着类路径上的 jndi.properties 将不会被读取。
你的代码应该是这样的:
Context context = new InitialContext();
ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("ConnectionFactory");
Queue queue = (Queue) context.lookup("MyQueue");
您可以设置静态属性以及从文件中检索它们,如下所示:
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,这会很有帮助。