gpt4 book ai didi

尝试从 Glassfish 获取 JMS 资源时出现 javax.naming.NoInitialContextException

转载 作者:太空宇宙 更新时间:2023-11-04 14:05:05 25 4
gpt4 key购买 nike

我是 JMS 新手,正在尝试使用 Glassfish 应用服务器执行我的第一个 JMS 程序。

我已在 Glassfish 管理控制台中创建了连接工厂 [jms/MyQueueFactory] ​​和目标资源 [jms/myQueue],如下所示:

Connection factory: jms/MyQueueFactory

Queue: jms/myQueue

以下是我的代码:

import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.naming.InitialContext;

public class MyReceiver
{
public static void main(String[] args)
{
try
{
InitialContext ctx = new InitialContext();
QueueConnectionFactory f = (QueueConnectionFactory)ctx.lookup("jms/MyQueueFactory"); **// Getting error here**
QueueConnection con = f.createQueueConnection();
con.start();

QueueSession session = con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

Queue t = (Queue)ctx.lookup("jms/myQueue");

QueueReceiver receiver = session.createReceiver(t);

MyListener listner = new MyListener();
receiver.setMessageListener(listner);

System.out.println("Receiver1 is ready, waiting for messages...");
System.out.println("press Ctrl+c to shutdown...");

while(true)
{
Thread.sleep(1000);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

但是当我尝试执行时,它给出了以下错误:

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial at javax.naming.spi.NamingManager.getInitialContext(Unknown Source) at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source) at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source) at javax.naming.InitialContext.lookup(Unknown Source) at com.test.MyReceiver.main(MyReceiver.java:16)

请让我知道我在这里缺少什么。

谢谢。

最佳答案

由于您是从 IDE 运行应用程序,因此您需要一种连接到 Glassfish 服务器的方法。

为此,您必须在环境变量中设置一些属性,或者也可以创建 Properties 对象

    Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");
props.put(Context.URL_PKG_PREFIXES, "com.sun.enterprise.naming");
props.put(Context.PROVIDER_URL, "http://localhost:4848/");

InitialContext initialContext;
try {
initialContext = new InitialContext(props);

使用这个对象你可以初始化上下文。

关于尝试从 Glassfish 获取 JMS 资源时出现 javax.naming.NoInitialContextException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28939786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com