博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

java代码实现rabbitMQ请求

Posted on 2015-11-12 11:13  和风细雨汪汪  阅读(629)  评论(0编辑  收藏  举报

1、下载rabbitMQ的客户端,下载地址 http://www.rabbitmq.com/download.html

2、解压,并将后缀为.jar(可以不用包含junit.jar)的拷贝出来放入java的项目。

复制代码
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Send {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.11.188"); // mq ip
        factory.setPort(5672);// 端口号
        factory.setUsername("abc"); // rabbitMQ登录用户名
        factory.setPassword("abc123"); // rabbitMQ登录密码
        factory.setVirtualHost("hdware.adjust.host");
        Connection connection = null;
        connection = factory.newConnection();
        Channel channel = connection.createChannel();
        String sendStr = "需要发送的文本";
        // 发送
        channel.basicPublish("", "gz.hdwareinfo.queue", null,
                sendStr.getBytes("utf-8"));
        System.out.println("已发送" + sendStr);
        channel.close();
        connection.close();
    }
}
复制代码

 

复制代码消息队列的使用方法

 1 1、命名空间 using System.Messaging;
 2 
 3 2、默认存储路径 C:\WINDOWS\system32\msmq\storage
 4 
 5 3、创建消息队列:MessageQueue mq = MessageQueue.Create(@".\Private$\LeeMSMQ");
 6 
 7 4、删除队列:MessageQueue.Delete(@".\Private$\LeeMSMQ");
 8 
 9 5、发送消息:MessageQueue mq = new MessageQueue(@".\Private$\LeeMSMQ");
10 mq.Send("sayhello1,hello msmq!", "sayhello1");
11 mq.Send("sayhello2,hello msmq!", "sayhello2");
12 
13 6、接受并删除消息:MessageQueue mq = new MessageQueue(@".\Private$\LeeMSMQ")
14 Message msg = mq.Receive();//引用的队列中可用的第一条消息
15 
16 7、接受但不删除消息:Message msg = mq.Peek();
17 8、删除所有消息: Message msg = mq.Purge();
18 
19 9、返回本机所有私有队列的消息
20 //返回本机所有私有队列的消息
21  foreach (MessageQueue mq in MessageQueue.GetPrivateQueuesByMachine("liyanping"))
22 {
23     mq.Formatter = new XmlMessageFormatter(new string[] { "System.String" });
24     Message[] msg = mq.GetAllMessages();
25     foreach (Message m in msg)
26     {
27         Console.WriteLine("label:{0},body:{1}", m.Label, m.Body);
28     }
29 }
30 
31 10、返回指定队列的消息
32 if (MessageQueue.Exists(@".\Private$\LeeMSMQ"))//判断私有消息是否存在
33 {
34     using (MessageQueue mq = new MessageQueue(@".\Private$\LeeMSMQ"))
35     {
36         mq.Formatter = new XmlMessageFormatter(new string[] { "System.String" });//设置消息队列格式化器
37         Message msg = mq.Receive();//接收消息
38         Console.WriteLine("label:{0},body: {1}", msg.Label, msg.Body);//输出消息
39         MessageQueue.Delete(@".\Private$\LeeMSMQ");
40     }
41 }