简单Java实例rabbitMQ

来源:互联网 发布:网络反向毒奶什么意思 编辑:程序博客网 时间:2024/04/30 05:20
下面来演示一个使用java的简单实例:
1、首先是消息生产者和提供者的基类
package com.lin;import java.io.IOException;import com.rabbitmq.client.Channel;import com.rabbitmq.client.Connection;import com.rabbitmq.client.ConnectionFactory; /** *  * 功能概要: EndPoint类型的队列 *  * @author linbingwen * @since  2016年1月11日 */public abstract class EndPoint{         protected Channel channel;    protected Connection connection;    protected String endPointName;         public EndPoint(String endpointName) throws IOException{         this.endPointName = endpointName;                  //Create a connection factory         ConnectionFactory factory = new ConnectionFactory();                  //hostname of your rabbitmq server         factory.setHost("10.75.4.25");         factory.setPort(5672);         factory.setUsername("asdf");         factory.setPassword("123456");                  //getting a connection         connection = factory.newConnection();                  //creating a channel         channel = connection.createChannel();                  //declaring a queue for this channel. If queue does not exist,         //it will be created on the server.         channel.queueDeclare(endpointName, false, false, false, null);    }              /**     * 关闭channel和connection。并非必须,因为隐含是自动调用的。     * @throws IOException     */     public void close() throws IOException{         this.channel.close();         this.connection.close();     }}

2、消息提供者
package com.lin.producer;import java.io.IOException;import java.io.Serializable;import org.apache.commons.lang.SerializationUtils;import com.lin.EndPoint;  /** *  * 功能概要:消息生产者 *  * @author linbingwen * @since  2016年1月11日 */public class Producer extends EndPoint{         public Producer(String endPointName) throws IOException{        super(endPointName);    }     public void sendMessage(Serializable object) throws IOException {        channel.basicPublish("",endPointName, null, SerializationUtils.serialize(object));    }  }

3、消息消费者
package com.lin.consumer;import java.io.IOException;import java.util.HashMap;import java.util.Map;import org.apache.commons.lang.SerializationUtils;import com.lin.EndPoint;import com.rabbitmq.client.AMQP.BasicProperties;import com.rabbitmq.client.Consumer;import com.rabbitmq.client.Envelope;import com.rabbitmq.client.ShutdownSignalException;  /** *  * 功能概要:读取队列的程序端,实现了Runnable接口 *  * @author linbingwen * @since  2016年1月11日 */public class QueueConsumer extends EndPoint implements Runnable, Consumer{         public QueueConsumer(String endPointName) throws IOException{        super(endPointName);           }         public void run() {        try {            //start consuming messages. Auto acknowledge messages.            channel.basicConsume(endPointName, true,this);        } catch (IOException e) {            e.printStackTrace();        }    }     /**     * Called when consumer is registered.     */    public void handleConsumeOk(String consumerTag) {        System.out.println("Consumer "+consumerTag +" registered");        }     /**     * Called when new message is available.     */    public void handleDelivery(String consumerTag, Envelope env,            BasicProperties props, byte[] body) throws IOException {        Map map = (HashMap)SerializationUtils.deserialize(body);        System.out.println("Message Number "+ map.get("message number") + " received.");             }     public void handleCancel(String consumerTag) {}    public void handleCancelOk(String consumerTag) {}    public void handleRecoverOk(String consumerTag) {}    public void handleShutdownSignal(String consumerTag, ShutdownSignalException arg1) {}}

4、测试
package com.lin.test;import java.io.IOException;import java.sql.SQLException;import java.util.HashMap;import com.lin.consumer.QueueConsumer;import com.lin.producer.Producer; public class Test {    public Test() throws Exception{                 QueueConsumer consumer = new QueueConsumer("queue");        Thread consumerThread = new Thread(consumer);        consumerThread.start();                 Producer producer = new Producer("queue");                 for (int i = 0; i < 1000000; i++) {            HashMap message = new HashMap();            message.put("message number", i);            producer.sendMessage(message);            System.out.println("Message Number "+ i +" sent.");        }    }         /**     * @param args     * @throws SQLException     * @throws IOException     */    public static void main(String[] args) throws Exception{      new Test();    }}
其中引入的jar包:
<!-- rabbitmq客户端 --><dependencies><dependency><groupId>com.rabbitmq</groupId><artifactId>amqp-client</artifactId><version>3.0.4</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.1</version></dependency></dependencies>

测试结果:
在提供消息
在消费消息 
然后同时打开rabbitmq的服务端,输入如下:
rabbitmqctl list_queues
这个命令是用来查看服务端中有多处个消息队列的。
可以看到有个名为queue的消息队列(更好的方法是安装好web监控插件,笔者一直安装失败,所以这里就不展示了)
0 0
原创粉丝点击