要解决ActiveMQ Artemis无法传送保留消息的问题,您可以尝试使用以下代码示例:
import org.apache.activemq.artemis.api.core.*;
import org.apache.activemq.artemis.api.core.client.*;
import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl;
import org.apache.activemq.artemis.core.server.embedded.EmbeddedActiveMQ;
public class Main {
public static void main(String[] args) throws Exception {
// 创建EmbeddedActiveMQ服务器
ConfigurationImpl configuration = new ConfigurationImpl();
configuration.setPersistenceEnabled(true); // 启用持久化
EmbeddedActiveMQ server = new EmbeddedActiveMQ();
server.setConfiguration(configuration);
// 启动服务器
server.start();
// 创建接收者
ConnectionFactory connectionFactory = ActiveMQClient.createServerConnectionFactory("tcp://localhost:61616");
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession();
Queue queue = session.createQueue("myQueue");
// 创建发送者
ConnectionFactory producerConnectionFactory = ActiveMQClient.createServerConnectionFactory("tcp://localhost:61616");
Connection producerConnection = producerConnectionFactory.createConnection();
Session producerSession = producerConnection.createSession();
Queue producerQueue = producerSession.createQueue("myQueue");
// 发送消息
MessageProducer producer = producerSession.createProducer(producerQueue);
producer.setDeliveryMode(DeliveryMode.PERSISTENT); // 设置持久化
TextMessage message = producerSession.createTextMessage("Hello World");
producer.send(message);
// 接收消息
MessageConsumer consumer = session.createConsumer(queue);
connection.start();
Message receivedMessage = consumer.receive();
System.out.println("Received message: " + ((TextMessage) receivedMessage).getText());
// 关闭连接和服务器
consumer.close();
session.close();
connection.close();
producer.close();
producerSession.close();
producerConnection.close();
server.stop();
}
}
请注意,上述代码示例假定您已将ActiveMQ Artemis服务器配置为使用持久化存储。您可以根据需要调整代码以适应自己的环境和要求。