gpt4 book ai didi

java - ActiveMQ 中的字符串生成器

转载 作者:行者123 更新时间:2023-12-01 13:54:41 25 4
gpt4 key购买 nike

因此,我有一个发送者(在本例中)向接收者发送 3 个 xml 格式的对象,但是我的字符串生成器首先打印出第一个对象,然后是第一个 + 第二个,然后是所有 3 个对象,而不是:- 先打印出来- 打印第二个- 打印第三个

这是我的代码:

public class TrackingSender {
public static void main(String[] args) {
try {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");

Connection connection = connectionFactory.createConnection();
connection.start();

Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

Destination destination = session.createQueue("TEST.SENDRECEIVE");

MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
TrackingInformatieFactory.makeTrackingInformatieList();
List<TrackingInformatie> trackingInformatieList = TrackingInformatieFactory.getTrackingInformatieList();
Writer writer = new StringWriter();
TextMessage message;
for(TrackingInformatie ti: trackingInformatieList){
Marshaller.marshal(ti, writer);
message = session.createTextMessage(writer.toString());
producer.send(message);
Thread.sleep(1000);
}

} catch(Exception e){
e.printStackTrace();
}
}

}

public class TrackingReceiver {
public static void main(String[] args) {
try {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");

Connection connection = connectionFactory.createConnection();
connection.start();

Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("TEST.SENDRECEIVE");
MessageConsumer consumer = session.createConsumer(destination);
TextMessage message;
Reader reader;
StringBuilder builder;
int charsRead;
char[] chars;
TrackingInformatieFactory.makeTrackingInformatieList();
List<TrackingInformatie> trackingInformatieList = TrackingInformatieFactory.getTrackingInformatieList();
for (int i = 0; i < trackingInformatieList.size(); i++){
message = (TextMessage) consumer.receive();
reader = new StringReader(message.getText());
builder = new StringBuilder();
chars = new char[100];
charsRead = -1;
do{
charsRead = reader.read(chars,0,chars.length);
//if we have valid chars, append them to end of string.
if(charsRead>0)
builder.append(chars,0,charsRead);
}
while(charsRead>0);
String stringReadFromReader = builder.toString();
System.out.println("String read = " + stringReadFromReader);

}
}
catch (Exception e) {
e.printStackTrace();
}
}
}

最佳答案

在你的 Producer 中,你永远不会重新初始化你的 writer。因此,您发送的消息实际上包含第一个对象、第一个对象和第二个对象,然后包含所有三个对象。更改生产者代码以在 for 循环内而不是之前初始化 StringWriter。

关于java - ActiveMQ 中的字符串生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19683258/

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