• RabbitMQ之Helloworld


    RabbitMQ介绍

    RabbitMQ是一个消息代理。它的核心原理非常简单:接收和发送消息。

    专有名词

    • 生产(Producing)意思就是发送。发送消息的程序就是一个生产者(producer)。我们一般用"P"来表示:

    • 队列(queue)就是邮箱的名称。消息通过你的应用程序和RabbitMQ进行传输,它们能够只存储在一个队列(queue)中。 队列(queue)没有任何限制,你要存储多少消息都可以——基本上是一个无限的缓冲。多个生产者(producers)能够把消息发送给同一个队列,同样,多个消费者(consumers)也能攻从一个队列(queue)中获取数据。队列可以化城这样(图上是队列的名称):

    • 消费(Consuming)和获取消息是一样的意思。一个消费者(consumer)就是一个等待获取消息的程序。我们把它画作"C":

    RabbitMQ安装

    1、下载源代码

    需要Erlang,访问需要pika

    http://www.rabbitmq.com/releases/rabbitmq-server/v3.3.4/

    解压mv到指定路径

    [root@typhoeus79 rabbitmq]# pwd
    /data1/guosong/rabbitmq
    [root@typhoeus79 rabbitmq]# ll
    total 36
    drwxr-xr-x 2 root root 12288 Jun 24 20:02 ebin
    drwxr-xr-x 3 root root  4096 Jun 24 20:02 etc
    drwxr-xr-x 2 root root  4096 Jun 24 20:02 include
    drwxr-xr-x 2 root root  4096 Jun 24 20:02 plugins
    drwxr-xr-x 2 root root  4096 Jun 24 20:02 sbin
    drwxr-xr-x 3 root root  4096 Jun 24 20:02 share
    drwxr-xr-x 4 root root  4096 Jul  1 20:08 var
    

     2、设置环境配置文件以及系统配置文件

    [root@typhoeus79 rabbitmq]# pwd
    /data1/guosong/rabbitmq/etc/rabbitmq
    [root@typhoeus79 rabbitmq]# ll
    total 24
    -rw-r--r-- 1 root root 18245 Jul  1 20:06 rabbitmq.config
    -rw-r--r-- 1 root root   204 Jul  1 20:07 rabbitmq-env.conf
    

     http://www.rabbitmq.com/configure.html#configuration-file

    [root@typhoeus79 rabbitmq]# more rabbitmq-env.conf 
    #example rabbitmq-env.conf file entries
    #Rename the node
    NODENAME=rabbit@typhoeus79 
    #Config file location and new filename bunnies.config
    CONFIG_FILE=/data1/guosong/rabbitmq/etc/rabbitmq/rabbitmq.config
    

     3、修改路径SYS_PREFIX

    [root@typhoeus79 sbin]# pwd
    /data1/guosong/rabbitmq/sbin
    [root@typhoeus79 sbin]# vim rabbitmq-defaults
    

     只修改SYS_PREFIX

    ### next line potentially updated in package install steps
    SYS_PREFIX=/data1/guosong/rabbitmq
    
    ### next line will be updated when generating a standalone release
    ERL_DIR=
    
    CLEAN_BOOT_FILE=start_clean
    SASL_BOOT_FILE=start_sasl
    
    ## Set default values
    
    CONFIG_FILE=${SYS_PREFIX}/etc/rabbitmq/rabbitmq
    LOG_BASE=${SYS_PREFIX}/var/log/rabbitmq
    MNESIA_BASE=${SYS_PREFIX}/var/lib/rabbitmq/mnesia
    ENABLED_PLUGINS_FILE=${SYS_PREFIX}/etc/rabbitmq/enabled_plugins
    
    PLUGINS_DIR="${RABBITMQ_HOME}/plugins"
    
    CONF_ENV_FILE=${SYS_PREFIX}/etc/rabbitmq/rabbitmq-env.conf  
    

     4、启动

    [root@typhoeus79 sbin]# ./rabbitmq-server -detached 
    #以后台模式启动
    

     5、状态查看以及停止

    [root@typhoeus79 sbin]# ./rabbitmqctl status
    Status of node rabbit@typhoeus79 ...
    [{pid,4717},
     {running_applications,[{rabbit,"RabbitMQ","3.3.4"},
                            {os_mon,"CPO  CXC 138 46","2.2.14"},
                            {mnesia,"MNESIA  CXC 138 12","4.11"},
                            {xmerl,"XML parser","1.3.6"},
                            {sasl,"SASL  CXC 138 11","2.3.4"},
                            {stdlib,"ERTS  CXC 138 10","1.19.4"},
                            {kernel,"ERTS  CXC 138 10","2.16.4"}]},
     {os,{unix,linux}},
     {erlang_version,"Erlang R16B03-1 (erts-5.10.4) [source] [64-bit] [smp:8:8] [async-threads:30] [hipe] [kernel-poll:true]
    "},
     {memory,[{total,62792432},
              {connection_procs,2800},
              {queue_procs,5600},
              {plugins,0},
              {other_proc,13833408},
              {mnesia,60272},
              {mgmt_db,0},
              {msg_index,25432},
              {other_ets,763072},
              {binary,15432},
              {code,16434300},
              {atom,602729},
              {other_system,31049387}]},
     {alarms,[]},
     {listeners,[{clustering,25672,"::"},{amqp,5672,"0.0.0.0"}]},
     {vm_memory_high_watermark,0.4},
     {vm_memory_limit,6676812595},
     {disk_free_limit,50000000},
     {disk_free,133066321920},
     {file_descriptors,[{total_limit,287900},
                        {total_used,3},
                        {sockets_limit,259108},
                        {sockets_used,1}]},
     {processes,[{limit,1048576},{used,131}]},
     {run_queue,0},
     {uptime,21}]
    ...done.
    [root@typhoeus79 sbin]# ./rabbitmqctl stop
    Stopping and halting node rabbit@typhoeus79 ...
    ...done.
    

    5、安装插件

    [root@typhoeus79 rabbitmq]# rabbitmq-plugins enable rabbitmq_management
    The following plugins have been enabled:
      mochiweb
      webmachine
      rabbitmq_web_dispatch
      amqp_client
      rabbitmq_management_agent
      rabbitmq_management
    Plugin configuration has changed. Restart RabbitMQ for changes to take effect.
    

     查看所有插件

    [root@typhoeus79 rabbitmq]# rabbitmq-plugins list
    [e] amqp_client                       3.3.4
    [ ] cowboy                            0.5.0-rmq3.3.4-git4b93c2d
    [ ] eldap                             3.3.4-gite309de4
    [e] mochiweb                          2.7.0-rmq3.3.4-git680dba8
    [ ] rabbitmq_amqp1_0                  3.3.4
    [ ] rabbitmq_auth_backend_ldap        3.3.4
    [ ] rabbitmq_auth_mechanism_ssl       3.3.4
    [ ] rabbitmq_consistent_hash_exchange 3.3.4
    [ ] rabbitmq_federation               3.3.4
    [ ] rabbitmq_federation_management    3.3.4
    [E] rabbitmq_management               3.3.4
    [e] rabbitmq_management_agent         3.3.4
    [ ] rabbitmq_management_visualiser    3.3.4
    [ ] rabbitmq_mqtt                     3.3.4
    [ ] rabbitmq_shovel                   3.3.4
    [ ] rabbitmq_shovel_management        3.3.4
    [ ] rabbitmq_stomp                    3.3.4
    [ ] rabbitmq_test                     3.3.4
    [ ] rabbitmq_tracing                  3.3.4
    [e] rabbitmq_web_dispatch             3.3.4
    [ ] rabbitmq_web_stomp                3.3.4
    [ ] rabbitmq_web_stomp_examples       3.3.4
    [ ] sockjs                            0.3.4-rmq3.3.4-git3132eb9
    [e] webmachine                        1.10.3-rmq3.3.4-gite9359c7
    

    查看15672端口是否存在

    [root@typhoeus79 rabbitmq]# lsof -i:15672
    COMMAND   PID USER   FD   TYPE     DEVICE SIZE NODE NAME
    beam.smp 7743 root   17u  IPv4 1717284623       TCP *:15672 (LISTEN)

    6、界面查看

    使用guest用户,默认只支持localhost访问

    如果需要远程访问的话,需要重新创建用户,否则访问失败

    #创建用户与密码
    [root@typhoeus79 rabbitmq]# rabbitmqctl add_user guosong 123456
    Creating user "guosong" ...
    ...done.
    
    #为用户设置权限
    set_permissions [-p <vhostpath>] <user> <conf> <write> <read> [root@typhoeus79 rabbitmq]# rabbitmqctl set_permissions -p "/" guosong ".*" ".*" ".*" Setting permissions for user "guosong" in vhost "/" ... ...done. #查看用户权限 [root@typhoeus79 rabbitmq]# rabbitmqctl list_user_permissions guosong Listing permissions for user "guosong" ... / .* .* .* ...done. #查看现有用户 [root@typhoeus79 rabbitmq]# rabbitmqctl list_users Listing users ... guest [administrator] guosong [] ...done. #设置用户为管理员
    set_user_tags <username> <tag> ... [root@typhoeus79 rabbitmq]# rabbitmqctl set_user_tags guosong administrator Listing users ... guest [administrator] guosong [administrator] ...done. #查看用户权限 [root@typhoeus79 rabbitmq]# rabbitmqctl list_users Listing users ... guest [administrator] guosong [administrator] ...done. #删除默认用户 [root@typhoeus79 rabbitmq]# rabbitmqctl delete_user guest Deleting user "guest" ... ...done. [root@typhoeus79 rabbitmq]# rabbitmqctl list_users Listing users ... guosong [administrator] ...done.

    远程访问成功:

    例子1:生产者和消费者

    消息的产生者send.py

    guosong@guosong:~/code/rabbitmq$ more send.py 
    #!/usr/bin/env python
    #-*- coding:utf8 -*-
    
    import pika
    
    def send():
        try:
            pika.connection.Parameters.DEFAULT_HOST='localhost'
    
            #连接队列
            para = pika.connection.Parameters()
            connection = pika.BlockingConnection(para)
            channel = connection.channel()
    
            #创建一个名伪hello的队列,然后把消息发送到这个队列中
            #如果把消息发送到一个不存在的队列,RabbitMQ会把这个消息丢弃
            channel.queue_declare(queue='hello')
    
            #发送第一条消息,只包含一个Hello World字符串,发送到hello队列中
            #在RabbitMQ中,消息不能直接发送到队列,需要发送交换器exchange中
            #exchange使用默认值,一个空字符串
            #routing_key参数指定伪队列的名称
            channel.basic_publish(exchange='',routing_key='hello',body='Hello World!')
    
            print "[x] Send 'Hello World!'"
    
    
            connection.close()
        except Exception,e:
            print "Error=%s" % str(e)
    
    if __name__ == '__main__':
        send()
    

    存在的问题是:

    guosong@guosong:~/code/rabbitmq$ ./send.py 
    [x] Send 'Hello World!'
    No handlers could be found for logger "pika.adapters.base_connection"
    
    #原因待查,百度没有搜到,google被墙了
    

    解决方案:

    添加如下代码

    import logging
    logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.CRITICAL)  
    

      

    消息的消费者 receive.py 

    guosong@guosong:~/code/rabbitmq$ more receive.py 
    #!/usr/bin/env python2.7
    #-*-coding:utf8 -*-
    import pika
    
    def callback(ch,method,properties,body):
        """对于消息的处理,需要定义一个回调函数
           当获取到消息的时候,pika库就会调用这个回调函数
           本例子就只是将内容打印到屏幕上
        """
    
        print " [x] Received %r" % (body,)
    
    def receive():
        try:
            #连接RabbitMQ服务器
            connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
    
            channel = connection.channel()
    
            #queue_declare创建一个队列,可以运行很多次,但是只有一个队列会创建
            #如果确定队列是已经存在的话,可以不这么做,前提是send.py先运行已经产生这个队列
            #如果并不确定哪个程序先运行,这种情况的话在程序中重复声明是好的做法
            channel.queue_declare(queue='hello')
    
            print "[*]Waiting for messages. To exit press CTRL+C"
    
            #告诉RabbitMQ这个回调函数将会从hello队列中接收消息
            channel.basic_consume(callback,queue='hello',no_ack=True)
    
            #输入一个无限循环来等待消息数据并运行回调函数
            channel.start_consuming()
        except Exception,e:
            print "Exception:%s" % str(e)
    
    
    if __name__ == '__main__':
        try:
            receive()
        except KeyboardInterrupt,e:
            print "Quit"
    

    运行结果:

    guosong@guosong:~/code/rabbitmq$ ./receive.py 
    [*]Waiting for messages. To exit press CTRL+C
     [x] Received 'Hello World!'
     [x] Received 'Hello World!'
     [x] Received 'Hello World!'
     [x] Received 'Hello World!'
     [x] Received 'Hello World!'
     [x] Received 'Hello World!'
     [x] Received 'Hello World!'
     [x] Received 'Hello World!'
     [x] Received 'Hello World!'
    ^CQuit
    

    参考链接

    http://www.cnblogs.com/chinaboard/p/3819533.html

    http://www.rabbitmq.com/install-generic-unix.html

    http://adamlu.net/rabbitmq/tutorial-one-python

    http://www.rabbitmq.com/man/rabbitmqctl.1.man.html

    https://github.com/pika/pika/issues/362

  • 相关阅读:
    js获取url参数
    Ueditor百度编辑器中的 setContent()方法的使用
    js防止sql注入的参数过滤
    父级元素点击,遮盖了子元素的点击
    input onchange事件
    jq选择子元素
    nodejs mysql 执行多条sql语句
    java.util.ConcurrentModificationException
    Group by与having理解
    ibatis配置xml文件中CDATA的用法
  • 原文地址:https://www.cnblogs.com/gsblog/p/3796084.html
Copyright © 2020-2023  润新知