RabbitMQ的代碼學習(生產者)

(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();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章