当前位置: 首页 > 工具软件 > Qpid > 使用案例 >

Qpid之Producer的示例

盖玉石
2023-12-01

QpidSender的code:

import org.apache.qpid.QpidException;
import org.apache.qpid.client.AMQAnyDestination;
import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.message.JMSBytesMessage;
import org.apache.qpid.url.URLSyntaxException;

import javax.jms.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;

public class QpidSender {
    public static void main(String[] rgs) {
        try {
            Connection connection = new AMQConnection("amqp://guest:guest@test/?brokerlist='tcp://192.168.xx.xx:5672'");
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination queue = new AMQAnyDestination("ADDR:Test; {create:always,assert:always,node:{type:topic,durable:true,x-declare:{exclusive:true,auto-delete:true}}}");
            MessageProducer producer = session.createProducer(queue);

            //text - TextMessage
            TextMessage textMessage = session.createTextMessage();
            textMessage.setText("01010101010101");
            producer.send(textMessage);
            System.out.println(textMessage.toString());

            //byte - JMSBytesMessage
//            JMSBytesMessage jmsBytesMessage = (JMSBytesMessage) session.createBytesMessage();
//            byte[] content = getFileByte("C:\\Users\\Desktop\\test.text");
//            jmsBytesMessage.writeBytes(content);
//            producer.send(jmsBytesMessage);

            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        } catch (QpidException e) {
            e.printStackTrace();
        } catch (URLSyntaxException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取文件字节流
     * @param filename
     * @return
     */
    private static byte[] getFileByte(String filename){
        byte[] buffer = null;
        FileInputStream fin = null;
        try {
            File file = new File(filename);
            fin = new FileInputStream(file);
            buffer = new byte[fin.available()];
            fin.read(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer;
    }
}

Receiver和其他示例可参考官方文档,如:
http://qpid.apache.org/releases/qpid-java-6.1.5/qpid-jms/examples/index.html

 类似资料: