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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值