yii2 amqp 接收和发送数据(和外部系统对接)

  1. 配置queue(amqp)
'bootstrap' => [
        'queue', // The component registers own console commands
    ],
    
    'components' => [
        'queue' => [
            'class' => 'zhuravljov\yii\queue\amqp\Queue',
            'host'  => '192.168.221.56',
            'port'  => 5672,
            'user'  => 'admin',
            'password' => 'admin',
            'queueName' => 'productDropshipQN',
            'exchangeName' => 'productDropshipEX',
        ],
    ],

 

2.console  controller

 

<?php
/**
 * FecShop file.
 *
 * @link http://www.fecshop.com/
 * @copyright Copyright (c) 2016 FecShop Software LLC
 * @license http://www.fecshop.com/license/
 */

namespace fecshop\app\console\modules\Amqp\controllers;

use Yii;
use yii\console\Controller;
use fecshop\app\console\modules\Amqp\block\PushTest;

use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

/**
 * @author Terry Zhao <2358269014@qq.com>
 * @since 1.0
 * 这是一个测试RabbitMq 的一个例子。这里作为消息生产方。
 * 你可以通过执行 ./yii amqp/test/test 来生产数据。
 */
class TestController extends Controller
{
    const EXCHANGE_DIRECT = 'direct';
    const EXCHANGE_TOPIC = 'topic';
    const EXCHANGE_FANOUT = 'fanout';
    
    public $host = '192.168.221.56';
    public $port = 5672;
    public $user = 'admin';
    public $password        = 'admin';
    
    public $queueName       = 'productDropshipQN';
    public $exchangeName    = 'productDropshipEX';
    public $routingKey      = 'productDropshipRT';
    public $exchangeType    = self::EXCHANGE_DIRECT;
    
    /**
     * @var AMQPStreamConnection
     */
    private $connection;
    /**
     * @var AMQPChannel
     */
    private $channel;
    
     /**
     * 生产数据
     */
    public function actionTest()
    {
        Yii::$app->queue->push([
            'name'  => 'water',
            'age'   => 331,
        ]);
    }
    /**
     * 接收数据
     */
    public function actionListen()
    {
        $this->open();
        $callback = function(AMQPMessage $message) {
            if ($this->handleMessage($message->body)) {
                $message->delivery_info['channel']->basic_ack($message->delivery_info['delivery_tag']);
            }
        };
        $this->channel->basic_qos(null, 1, null);
        $this->channel->basic_consume($this->queueName, '', false, false, false, false, $callback);
        while(count($this->channel->callbacks)) {
            $this->channel->wait();
        }
        
    }
    
    
    /**
     * Opens connection and channel
     */
    protected function open()
    {
        if ($this->channel) return;
        $this->connection = new AMQPStreamConnection($this->host, $this->port, $this->user, $this->password);
        $this->channel = $this->connection->channel();
        $this->channel->queue_declare($this->queueName,true, true);
        $this->channel->exchange_declare($this->exchangeName, $this->exchangeType, false, true, false);
        $this->channel->queue_bind($this->queueName, $this->exchangeName,$this->routingKey);
    }
    /**
     * 这里处理接收到的数据
     */
    protected function handleMessage($message)
    {
        // $message = unserialize($message);
        var_dump($message);
        //  do some thing ...
        // \Yii::info($message,'fecshop_debug');
        return true;
    }
    
    
    
    /*
    public function actionListen3()
    {
          Yii::$app->queue->listen();
        
    }
    */
    
}

 

 

 

 

vagrant 设置文件映射,将windows文件夹映射到linux中

首先,我们为什么要这样做?

我们用vagrant搭建起来了linux环境,也就是在windows下面虚拟出来的linux环境,但是,可以用如下的几种方式进行编辑:

1.如果我们用vim进行编辑,是非常费劲的,不提倡

2.通过编辑器的ftp直连,就像:

Linux 作为开发环境的方法分享

这种方式只能用notepad这种,只在连接的时候加载,而不能用phpstorm这种提前加载到本地,因为这种方式,用phpstorm会造成一定的问题,我的开发环境用的是阿里云主机,随便找个电脑安装个notepad就可以干活了,也就说这种方式比较适合远程。

3. 最通用的方式,就是本地window通过vagrant虚拟出来一个linux,然后,通过映射的方式,将windows下的文件夹映射到vagrant的linux中,然后,我们的编辑器(phpstorm)加载window下的这个文件夹,就可以了,当我们修改window下的这个文件夹,因为是挂载到linux的(有点像u盘的感觉),我们把nginx指向该文件夹,就可以进行开发了(上面说的有点啰嗦,不过意思说明白了),这也就是本文要讲述的方式。

另外需要注意的是:
vagrant虚拟的linux的文件是无法映射到windows中的,只能windows的文件映射到linux中,就像window环境中的某个文件夹挂载到vagrant 的 linux中的感觉,但是不能把linux的文件夹挂载到windows,具体操作如下:

打开Vagrantfile,修改配置内容如下(完全修改):

# -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://atlas.hashicorp.com/search.
  config.vm.box = "centos-6.6-x86_64"
  
  config.vm.hostname = "dev"
  config.ssh.username = "root"
  config.ssh.password = "123456"
  config.ssh.insert_key = "true"
  config.ssh.shell = "bash -c 'BASH_ENV=/etc/profile exec bash'"
  config.ssh.forward_agent = true
  # Disable automatic box update checking. If you disable this, then
  # boxes will only be checked for updates when the user runs
  # `vagrant box outdated`. This is not recommended.
  # config.vm.box_check_update = false

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
   config.vm.network "forwarded_port", guest: 80, host: 80

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  config.vm.network "private_network", ip: "192.168.10.12"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  config.vm.network "public_network"

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  # config.vm.synced_folder "../data", "/vagrant_data"
    config.vm.synced_folder "D:\\linux\\fecshop", "/www/web/develop/fecshop"
  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  config.vm.provider "virtualbox" do |vb|
    # Display the VirtualBox GUI when booting the machine
    # vb.gui = true
    vb.name = "dev"
    # Customize the amount of memory on the VM:
    vb.memory = "2048"
  end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

  # Define a Vagrant Push strategy for pushing to Atlas. Other push strategies
  # such as FTP and Heroku are also available. See the documentation at
  # https://docs.vagrantup.com/v2/push/atlas.html for more information.
  # config.push.define "atlas" do |push|
  #   push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME"
  # end

  # Enable provisioning with a shell script. Additional provisioners such as
  # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
  # documentation for more information about their specific syntax and use.
  # config.vm.provision "shell", inline: <<-SHELL
  #   apt-get update
  #   apt-get install -y apache2
  # SHELL
end

在上面的配置中可以看到如下:

config.vm.synced_folder “D:\\linux\\fecshop”, “/www/web/develop/fecshop”

第一个路径是window的路径,第二个是vagrant’中linux的路径

启动,如图:

 

注意:

1.如果 /www/web/develop/fecshop 这个文件夹在linux中存在,那么启动后,原来的文件夹将看不到。

2. 如果linux存在文件夹/www/web/develop/fecshop,您想把这个文件夹的内容复制到映射后的/www/web/develop/fecshop中,那么,您可以先将/www/web/develop/fecshop  改名为 /www/web/develop/fecshop_cp,然后,添加映射配置,重启(vagrant reload)vagrant,然后通过命令复制过去即可

\cp -rf /www/web/develop/fecshop_cp/*  /www/web/develop/fecshop/

 

安装 RabbitMQ – centos 6

 

1.安装Erlang环境

cd /usr/local/src/  
mkdir rabbitmq  
cd rabbitmq  
  
wget http://packages.erlang-solutions.com/erlang-solutions-1.0-1.noarch.rpm  
rpm -Uvh erlang-solutions-1.0-1.noarch.rpm  
  
rpm --import http://packages.erlang-solutions.com/rpm/erlang_solutions.asc  
  
sudo yum install erlang

2.安装RabbitMQ

上面都成功后 安装RabbitMQ

wget https://www.rabbitmq.com/releases/rabbitmq-server/v3.6.1/rabbitmq-server-3.6.1-1.noarch.rpm
rpm --import https://www.rabbitmq.com/rabbitmq-signing-key-public.asc
yum install rabbitmq-server-3.6.1-1.noarch.rpm

安装输出log如下:

Loaded plugins: security
Setting up Install Process
Examining rabbitmq-server-3.6.1-1.noarch.rpm: rabbitmq-server-3.6.1-1.noarch
Marking rabbitmq-server-3.6.1-1.noarch.rpm to be installed
Resolving Dependencies
--> Running transaction check
---> Package rabbitmq-server.noarch 0:3.6.1-1 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

===================================================================================================================
 Package                    Arch              Version             Repository                                  Size
===================================================================================================================
Installing:
 rabbitmq-server            noarch            3.6.1-1             /rabbitmq-server-3.6.1-1.noarch            5.5 M

Transaction Summary
===================================================================================================================
Install       1 Package(s)

Total size: 5.5 M
Installed size: 5.5 M
Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : rabbitmq-server-3.6.1-1.noarch                                                                  1/1 
  Verifying  : rabbitmq-server-3.6.1-1.noarch                                                                  1/1 

Installed:
  rabbitmq-server.noarch 0:3.6.1-1                                                                                 

Complete!

run the following command to allow SELinux to enable RabbitMQ service:

setsebool -P nis_enabled 1

开启端口,如果是本地测试,关掉iptables也可以

4369 (epmd), 25672 (Erlang distribution)
 5672, 5671 (AMQP 0-9-1 without and with TLS)
 15672 (if management plugin is enabled)
 61613, 61614 (if STOMP is enabled)
 1883, 8883 (if MQTT is enabled)

启动:

/etc/init.d/rabbitmq-server start

log如下:

[root@iZ942k2d5ezZ tools]# /etc/init.d/rabbitmq-server start
Starting rabbitmq-server: SUCCESS
rabbitmq-server.

加入浏览器界面:

rabbitmq-plugins enable rabbitmq_management
chown -R rabbitmq:rabbitmq /var/lib/rabbitmq/

然后访问:

http://120.24.37.249:15672

就可以看到界面了:

RabbitMQ Management - Google Chrome_005

增加账户:

rabbitmqctl add_user mqadmin 123456
rabbitmqctl set_user_tags mqadmin administrator
rabbitmqctl set_permissions -p / mqadmin ".*" ".*" ".*"

 

上面的命令中

mqadmin就是登陆的账户

123456就是登陆的密码

然后就可以看到界面了,如下:

RabbitMQ Management

rabbitmq php 安装amqp扩展

一:安装rabbitmq-c-0.7.1

没有安装就会提示上面的错误
下载地址:https://github.com/alanxz/rabbitmq-c
我选择的是最新版本0.7.1

wget https://github.com/alanxz/rabbitmq-c/releases/download/v0.7.1/rabbitmq-c-0.7.1.tar.gz
tar zxf rabbitmq-c-0.7.1.tar.gz
 
cd rabbitmq-c-0.7.1
./configure --prefix=/usr/local/rabbitmq-c-0.7.1
make && make install

备注:如果下面的下载比较慢,您可以到百度云盘下载我下载下来的文件,云盘地址:http://pan.baidu.com/s/1kVwRD2Z#list/path=%2F,打开这个链接,找到文件rabbitmq-c-0.7.1.tar下载下来即可。

二:安装amqp

下载地址https://pecl.php.net/package/amqp
我选择的是1.6.1

!!!对于php7.1,需要下载高版本:

wget https://pecl.php.net/get/amqp-1.9.3.tgz   //php 7.1
wget https://pecl.php.net/get/amqp-1.6.1.tgz   // php 5.6
tar zxf amqp-1.6.1.tgz
cd amqp-1.6.1
 
/usr/local/php/bin/phpize
 
./configure --with-php-config=/usr/local/php/bin/php-config --with-amqp --with-librabbitmq-dir=/usr/local/rabbitmq-c-0.7.1

注意:这里的/usr/local/rabbitmq-c-0.7.1要跟上面rabbitmq-c安装的地址一样

make && make install

然后打开/etc/php.ini

添加配置:

extension=amqp.so

重启php,phpinfo就可以看到配置了

到这里就完成了,之前找了很多资料就会报错,唯有这个方式没有问题,我的linux是centos6,php版本5.4和7都安装通过了。

参考资料:https://www.phpsong.com/2223.html