RabbitMQ(六)远程连接

默认情况下,rabbitmq使用`guest`来连接本地(localhost)的server,当需要远程连接时,就会失效。

"guest" user can only connect via localhost

如果必须使用`guest`用户来进行远程登录,需要修改配置
[{rabbit, [{loopback_users, []}]}].

(1)那么首先需要创建并添加一个用户`test`,让其具有管理员权限

rabbitmqctl add_user rootroot 
rabbitmqctl set_user_tags rootadministrator 
rabbitmqctl set_permissions -p / root".*" ".*" ".*"

(2)修改配置文件

[{rabbit, [{loopback_users, ["root"]}]}].

(3)重启rabbitmq-server

/etc/init.d/rabbitmq-server restart

(4)修改host

修改远程客户端机器上的/etc/hosts,添加rabbit-server的IP
xx.xx.xx.xx rabbit-server

(5)认证

pika提供了两种认证方式:ConnectinParameters和URLParameters。

ConnectionParameters

RabbitMQ(六)远程连接
import pika

# Set the connection parameters to connect to rabbit-server1 on port 5672# on the / virtual host using the username "guest" and password "guest"
credentials = pika.PlainCredentials('root', 'root')
parameters = pika.ConnectionParameters('rabbit-server1',
                                       5672,
                                       '/',
                                       credentials)
RabbitMQ(六)远程连接

URLParameters

import pika

# Set the connection parameters to connect to rabbit-server1 on port 5672# on the / virtual host using the username "guest" and password "guest"
parameters = pika.URLParameters('amqp://guest:guest@rabbit-server1:5672/%2F')

例子

RabbitMQ(六)远程连接
import pika

i = 1

def callback(ch, method, properties, body):
    global i
    #print 'receive %r'%body
    print 'receive %s'%i
    i += 1
    f = open('%s'%i, 'w+')
    f.write(body)
    f.close()

#第一种方法
#credentials = pika.PlainCredentials('mtest', 'root')
#connection = pika.BlockingConnection(pika.ConnectionParameters('rabbit-server', 5672, '/', credentials))
#第二种方法
parameters = pika.URLParameters('amqp://mtest:root@rabbit-server:5672/%2F')
connection = pika.BlockingConnection(parameters)

channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_consume(callback, queue='hello1', no_ack=True)

channel.start_consuming()      
RabbitMQ(六)远程连接

 

RabbitMQ(六)远程连接
本文 由 cococo点点 创作,采用 知识共享 署名-非商业性使用-相同方式共享 3.0 * 许可协议进行许可。欢迎转载,请注明出处:
转载自:cococo点点 http://www.cnblogs.com/coder2012


上一篇:RabbitMQ(六)远程连接


下一篇:Rtti 单元(4): 获取结构的信息