gpt4 book ai didi

java - 设置 JMS 连接以便自动重新连接的理想方式

转载 作者:搜寻专家 更新时间:2023-10-31 20:22:10 25 4
gpt4 key购买 nike

我目前正在为持久订阅编写一个信使服务(它最终可能会变成非持久的,我们仍在讨论这个问题),我正在寻找一些关于如何处理我们的服务器因任何原因暂时停机的情况的建议我们需要自动重新订阅该主题。这是它如何连接的示例代码:

public void DurableChatter(String broker, String username, String password)
{
javax.jms.MessageProducer publisher = null;
javax.jms.MessageConsumer subscriber = null;
javax.jms.Topic topic = null;

//Create a connection:
try{
javax.jms.ConnectionFactory factory;
factory = (new progress.message.jclient.ConnectionFactory (broker));
connection = factory.createConnection (username, password);

//Durable Subscriptions are indexed by username, clientID and subscription name
//It is a good proactice to set the clientID:
connection.setClientID(CLIENT_ID);
pubSession = connection.createSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE);
subSession = connection.createSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE);
}
catch (javax.jms.JMSException jmse){
System.err.println ("Error: Cannot connect to Broker - " + broker);
jmse.printStackTrace();
System.exit(1);
}

//Create Publisher and Durable Subscriber:
try{

topic = pubSession.createTopic(APP_TOPIC);
subscriber = subSession.createDurableSubscriber(topic, "SampleSubscription");
subscriber.setMessageListener(this);
publisher = pubSession.createProducer(topic);
connection.start();
}
catch (javax.jms.JMSException jmse){
System.out.println("Error: connection not started.");
jmse.printStackTrace();
System.exit(1);
}

//Wait for user input

try
{
System.out.println("Enter text to send as message and press enter.");
java.io.BufferedReader stdin =
new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
while (true)
{
String s = stdin.readLine();

if(s == null){
exit();
}
else if (s.length()>0)
{
try
{
javax.jms.TextMessage msg = pubSession.createTextMessage();
msg.setText(username + ": " + s);
//Publish the message persistantly:
publisher.send(
msg, //message
javax.jms.DeliveryMode.PERSISTENT, //publish persistantly
javax.jms.Message.DEFAULT_PRIORITY,//priority
MESSAGE_LIFESPAN); //Time to Live
}
catch (javax.jms.JMSException jmse){
System.err.println("Error publishing message:" + jmse.getMessage());
}
}
}
}
catch (java.io.IOException ioe)
{
ioe.printStackTrace();
}
}

最佳答案

你应该让你的客户implement javax.jmsExceptionListener .

这将允许您的客户端在连接丢失时立即接收到来自 JMS API 的回调,即使您的应用程序此时没有绑定(bind)发布任何内容。

在创建 Connection、连接并启动它之后,调用 connection.setExceptionListener(myListener)。另请参阅 Connection 的 Javadoc .

关于java - 设置 JMS 连接以便自动重新连接的理想方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11583761/

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