activemq5.2發送和接收BlobMessage簡單一實例

來源:互聯網
上載者:User

package com.work.activemq;</p><p>/**<br /> * @author wangmingjie<br /> * @date 2009-7-29上午09:00:48<br /> */</p><p>import java.io.File;<br />import java.io.IOException;</p><p>import javax.jms.DeliveryMode;<br />import javax.jms.Destination;<br />import javax.jms.JMSException;<br />import javax.jms.MessageProducer;<br />import javax.jms.Session;</p><p>import org.apache.activemq.ActiveMQConnection;<br />import org.apache.activemq.ActiveMQConnectionFactory;<br />import org.apache.activemq.ActiveMQSession;<br />import org.apache.activemq.BlobMessage;<br />import org.apache.activemq.command.ActiveMQQueue;</p><p>public class BlobMessageSendTest {</p><p> private String user = ActiveMQConnection.DEFAULT_USER; </p><p> private String password = ActiveMQConnection.DEFAULT_PASSWORD; </p><p>// private String url = ActiveMQConnection.DEFAULT_BROKER_URL;<br /> private String url = "tcp://localhost:61616?jms.blobTransferPolicy.defaultUploadUrl=http://localhost:8161/fileserver/";</p><p> private String subject = "Blob Queue";</p><p> private Destination destination = null; </p><p> private ActiveMQConnection connection = null; </p><p> private ActiveMQSession session = null; </p><p> private MessageProducer producer = null; </p><p> // 初始化<br /> private void initialize() throws JMSException, Exception {<br /> ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory( url);<br /> connection = (ActiveMQConnection)connectionFactory.createConnection();<br /> /*<br /> * !!!!!!!!!!!!!!!!!!!!!!!!! very important. If it is set to true<br /> * (default) the uploader is lost in translation <br /> * !!!!!!!!!!!!!!!!!!!!!!!!!<br /> */<br /> connection.setCopyMessageOnSend(false);<br /> session = (ActiveMQSession)connection.createSession(false, Session.AUTO_ACKNOWLEDGE);<br /> destination = session.createQueue(subject);<br />// destination = session.createTopic(subject);<br /> producer = session.createProducer(destination);<br /> producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);<br /> } </p><p> // 發送訊息<br /> public void produceMessage(File file) throws JMSException, Exception {<br /> initialize();<br /> BlobMessage msg = session.createBlobMessage(file); </p><p> connection.start();<br /> System.out.println("Producer:->Sending message: " + file.getName());<br /> producer.send(msg);<br /> System.out.println("Producer:->Message sent complete!");<br /> } </p><p> // 關閉串連<br /> public void close() throws JMSException {<br /> System.out.println("Producer:->Closing connection");<br /> if (producer != null)<br /> producer.close();<br /> if (session != null)<br /> session.close();<br /> if (connection != null)<br /> connection.close();<br /> } </p><p> /**<br /> * 測試成功,能夠發送到伺服器上。<br /> * @param args<br /> * @throws IOException<br /> */<br /> public void send() throws IOException {</p><p> long start = System.currentTimeMillis();</p><p> /*<br /> * First you must tell how the Blob repository can be found. Use<br /> * ActiveMQ 5.1.0+ as broker because the fileserver webapp works there<br /> * out of the box.<br /> */<br /> ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(<br /> "tcp://localhost:61616?jms.blobTransferPolicy.defaultUploadUrl=http://localhost:8161/fileserver/");</p><p> ActiveMQConnection conn = null;<br /> ActiveMQSession session = null;<br /> try {<br /> conn = (ActiveMQConnection) cf.createConnection();<br /> session = (ActiveMQSession) conn.createSession(false,<br /> Session.AUTO_ACKNOWLEDGE);<br /> Destination destination = new ActiveMQQueue("Blob Queue");<br /> MessageProducer producer = session.createProducer(destination);</p><p> /*<br /> * !!!!!!!!!!!!!!!!!!!!!!!!! very important. If it is set to true<br /> * (default) the uploader is lost in translation <br /> * !!!!!!!!!!!!!!!!!!!!!!!!!<br /> */<br /> conn.setCopyMessageOnSend(false);</p><p>// File file = File.createTempFile("amq-data-file-", ".dat");<br />// // lets write some data<br />// BufferedWriter writer = new BufferedWriter(new FileWriter(file));<br />// writer.append("Hello World!");<br />// writer.close();<br /> File file = new File("d:/BUG管理需求和設計.doc");<br /> /*<br /> * i have used an simple ascii file instead of the picture you want<br /> * to use<br /> */<br /> BlobMessage message = session.createBlobMessage(file);</p><p> /*<br /> * should only work if you receive the message<br /> */<br /> // System.out.println(message.getInputStream());<br /> producer.send(message);</p><p> /*<br /> * After all you can see a new file under<br /> * $Brokerlocation$/webapps/fileserver/<br /> */<br /> } catch (JMSException e) {<br /> e.printStackTrace();<br /> } finally {<br /> try {<br /> if (session != null) {<br /> session.close();<br /> }<br /> if (conn != null) {<br /> conn.close();<br /> }<br /> } catch (JMSException ex) {<br /> }<br /> }<br /> System.out.println("共花費了"+(System.currentTimeMillis() - start)+"毫秒!");<br /> }</p><p>}<br />

 

package com.work.activemq;</p><p>import java.io.BufferedInputStream;<br />import java.io.File;<br />import java.io.FileOutputStream;<br />import java.io.IOException;<br />import java.io.InputStream;</p><p>import javax.jms.Destination;<br />import javax.jms.JMSException;<br />import javax.jms.Message;<br />import javax.jms.MessageConsumer;<br />import javax.jms.MessageListener;<br />import javax.jms.Session;<br />import javax.jms.TextMessage;</p><p>import org.apache.activemq.ActiveMQConnection;<br />import org.apache.activemq.ActiveMQConnectionFactory;<br />import org.apache.activemq.ActiveMQSession;<br />import org.apache.activemq.BlobMessage;</p><p>/**<br /> * @author wangmingjie<br /> * @date 2009-7-29上午09:05:10<br /> */<br />public class BlobMessageReceiveTest implements MessageListener {<br /> private String user = ActiveMQConnection.DEFAULT_USER; </p><p> private String password = ActiveMQConnection.DEFAULT_PASSWORD; </p><p>// private String url = ActiveMQConnection.DEFAULT_BROKER_URL;<br /> private String url = "tcp://localhost:61616?jms.blobTransferPolicy.defaultUploadUrl=http://localhost:8161/fileserver/";</p><p> private String subject = "Blob Queue"; </p><p> private Destination destination = null; </p><p> private ActiveMQConnection connection = null; </p><p> private ActiveMQSession session = null; </p><p> private MessageConsumer consumer = null; </p><p> private static int count = 1; //計數器</p><p> // 初始化<br /> private void initialize() throws JMSException, Exception {<br /> ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(<br /> url);<br /> connection = (ActiveMQConnection)connectionFactory.createConnection();<br />/*<br /> * !!!!!!!!!!!!!!!!!!!!!!!!! very important. If it is set to true<br /> * (default) the uploader is lost in translation <br /> * !!!!!!!!!!!!!!!!!!!!!!!!!<br /> */<br /> connection.setCopyMessageOnSend(false);<br /> session = (ActiveMQSession)connection.createSession(false, Session.AUTO_ACKNOWLEDGE);<br /> destination = session.createQueue(subject);<br />// destination = session.createTopic(subject);<br /> consumer = session.createConsumer(destination); </p><p> } </p><p> // 消費訊息<br /> public void consumeMessage() throws JMSException, Exception {<br /> initialize();<br /> connection.start(); </p><p> System.out.println("Consumer:->Begin listening...");<br /> // 開始監聽 </p><p> consumer.setMessageListener(this);<br /> // Message message = consumer.receive();<br /> } </p><p> // 關閉串連<br /> public void close() throws JMSException {<br /> System.out.println("Consumer:->Closing connection");<br /> if (consumer != null)<br /> consumer.close();<br /> if (session != null)<br /> session.close();<br /> if (connection != null)<br /> connection.close();<br /> } </p><p> // 訊息處理函數<br /> public void onMessage(Message message) {<br /> try {<br /> if (message instanceof TextMessage) {<br /> TextMessage txtMsg = (TextMessage) message;<br /> String msg = txtMsg.getText();<br /> System.out.println("Consumer:->Received: " + msg);<br /> }else if (message instanceof BlobMessage) {<br /> try {<br />InputStream inStr = ((BlobMessage)message).getInputStream();<br />BufferedInputStream bin = new BufferedInputStream(inStr);<br />File file = new File("c:/new.rar");<br />FileOutputStream fos = new FileOutputStream(file);</p><p>byte[] block = new byte[4096];//大小不同,檔案就可能損壞。<br />while (true) {<br />int readLength = bin.read(block);<br />if (readLength == -1)<br />break;// end of file<br />fos.write(block, 0, readLength); //一定要寫入實際讀取內容<br />}<br />bin.close();<br />inStr.close();<br />fos.flush();<br />fos.close();<br />System.out.println("第"+count+++"次Consumer:->Received BlobMessage wangmj ");<br />} catch (IOException e) {<br />e.printStackTrace();<br />}<br /> }else {<br /> System.out.println("Consumer:->Received: " + message);<br /> }<br /> } catch (JMSException e) {<br /> // TODO Auto-generated catch block<br /> e.printStackTrace();<br /> }<br /> } </p><p>}<br />

 

package com.work.activemq;

import java.io.File;

/**
 * @author wangmingjie
 * @date 2009-7-29上午09:21:53
 */
public class BlobMessageClient {

 /**
  * topic方式,必須先啟動消費者,然後是生產者,否則接收不到訊息。
  * queue方式,最好先啟動生產者,然後啟動消費者,否則也容易收不到訊息。
  * @param args
  */
 public static void main(String[] args) throws Exception {
  
  BlobMessageSendTest producer = new BlobMessageSendTest();   
  BlobMessageReceiveTest consumer = new BlobMessageReceiveTest();

        String fileName = "e:/javagood/clearbug1.6.zip";
//        String fileName = "d:/JAVA+開發視頻會議系統詳細設計.doc";
  File file = new File(fileName);
        producer.produceMessage(file);
       
        producer.close();   
        // 延時500毫秒之後停止接受訊息   
        Thread.sleep(2000);   
        // 開始監聽   
        consumer.consumeMessage();   
        // 延時500毫秒之後發送訊息
        Thread.sleep(2000); 
        consumer.close();   
 }

}

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.