2013-10-30 75 views
0

所以我有一個發送者(在本例中)發送3個xml格式的對象給接收者,但是我的stringbuilder首先打印出第一個對象,然後是第一個+第二個,然後是所有3個而不是: - 打印出第一 - 打印第二 - 打印第三ActiveMQ中的Stringbuilder

這是我的代碼:

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(); 
    } 
} 
} 

回答

1

在你的製片人,你永遠不會重新初始化您的作家。因此,您發送的消息實際上包含第一個對象,第一個和第二個對象,然後是全部三個。改變你的生產者代碼來初始化for循環中的StringWriter,而不是在它之前。

+0

謝謝!你是對的 –