(Python实现)
# coding: utf-8
import pika,os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
class SendRabbitMq:
def __init__(self,username,password,host,queueName,exchange,routing_key,body):
#mq用户名
self.username = username
#mq密码
self.password = password
#mq的ip地址
self.host = host
#队列名
self.queueName = queueName
#交换机名
self.exchange = exchange
#路由key
self.routing_key = routing_key
#发送消息内容
self.body = body
try:
#获得连接mq凭证
self.credentials = pika.PlainCredentials(self.username,self.password)
#连接mq
self.connection = pika.BlockingConnection(pika.ConnectionParameters(self.host,5672,'/',self.credentials))
#连接消息渠道
self.channel = self.connection.channel()
except Exception, e:
print e
def send(self):
#申明队列,durable=True:队列持久化
self.channel.queue_declare(queue=self.queueName,durable=True)
#发送消息,并制定交换机和路由key
self.channel.basic_publish(exchange=self.exchange, routing_key=self.routing_key, body=self.body)
print 'send OK',self.body
def close(self):
self.connection.close()
if __name__ == "__main__":
msg22 = "发送消息"
sendMessage = SendRabbitMq('username','password','192.168.0.1','excha','routingkey',msg22)
sendMessage.send()
sendMessage.close()
(java版本)
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class RabbitMQProducer {
public static void main(String[] args) throws IOException, TimeoutException {
//创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername("root");
factory.setPassword("123456");
//设置 RabbitMQ地址
factory.setHost("140.143.17.1");
//建立到代理服务器到连接
Connection conn = factory.newConnection();
//获得信道
Channel channel = conn.createChannel();
//声明交换器
String exchangeName = "hello";
channel.exchangeDeclare(exchangeName,"direct",true);
channel.queueDeclare("hello-exchange",false,false,false,null);
String routingKey = "hola";
//发布消息
byte[] messageBodyByte = "liyong0889".getBytes();
channel.basicPublish(exchangeName,routingKey,null,messageBodyByte);
System.out.print("send:"+messageBodyByte);
channel.close();
conn.close();
}
}