测试环境:centos7.6
,rabbitmq3.7.12
,php7.2.6
安装rabbitmqd参考:centos安装rabbitmq。
要在php中使用rabbitmq需要安装两个扩展:rabbitmq-c
和amqp
,这里使用的两个扩展都为已发布的最新版。
安装rabbitmq-c
扩展下载地址:https://github.com/alanxz/rabbitmq-c/releases
# 安装步骤的详细信息可以参考github地址
wget https://github.com/alanxz/rabbitmq-c/archive/v0.9.0-master.tar.gz
tar -zxvf v0.9.0-master.tar.gz
cd rabbitmq-c-0.9.0-master
mkdir build && cd build
cmake -DCMAKE_INSTALL_PREFIX=/usr/local/rabbitmq-c ..
cmake --build . --target install
安装amqp
扩展下载地址:http://pecl.php.net/package/amqp
wget http://pecl.php.net/get/amqp-1.9.4.tgz
tar -zxvf amqp-1.9.4.tgz
cd amqp-1.9.4
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config --with-amqp --with-librabbitmq-dir=/usr/local/rabbitmq-c
make && make install
这里在安装的时候报了一个错
[root@localhost amqp-1.9.4]# make && make install
/bin/sh /home/amqp-1.9.4/libtool --mode=link cc -DPHP_ATOM_INC -I/home/amqp-1.9.4/include -I/home/amqp-1.9.4/main -I/home/amqp-1.9.4 -I/usr/local/php/include/php -I/usr/local/php/include/php/main -I/usr/local/php/include/php/TSRM -I/usr/local/php/include/php/Zend -I/usr/local/php/include/php/ext -I/usr/local/php/include/php/ext/date/lib -I/usr/local/rabbitmq-c/include -DHAVE_CONFIG_H -g -O2 -o amqp.la -export-dynamic -avoid-version -prefer-pic -module -rpath /home/amqp-1.9.4/modules amqp.lo amqp_type.lo amqp_exchange.lo amqp_queue.lo amqp_connection.lo amqp_connection_resource.lo amqp_channel.lo amqp_envelope.lo amqp_basic_properties.lo amqp_methods_handling.lo amqp_timestamp.lo amqp_decimal.lo -Wl,-rpath,/usr/local/rabbitmq-c/lib -L/usr/local/rabbitmq-c/lib -lrabbitmq
cc -shared .libs/amqp.o .libs/amqp_type.o .libs/amqp_exchange.o .libs/amqp_queue.o .libs/amqp_connection.o .libs/amqp_connection_resource.o .libs/amqp_channel.o .libs/amqp_envelope.o .libs/amqp_basic_properties.o .libs/amqp_methods_handling.o .libs/amqp_timestamp.o .libs/amqp_decimal.o -L/usr/local/rabbitmq-c/lib -lrabbitmq -Wl,-rpath -Wl,/usr/local/rabbitmq-c/lib -Wl,-soname -Wl,amqp.so -o .libs/amqp.so
/usr/bin/ld: cannot find -lrabbitmq
collect2: error: ld returned 1 exit status
make: *** [amqp.la] 错误 1
发现/usr/local/rabbitmq-c
目录下没有lib文件夹,有个lib64,然后把拷贝了一份lib目录,问题解决了。
cp -r /usr/local/rabbitmq-c/lib64 /usr/local/rabbitmq-c/lib
添加amqp扩展
vi /usr/local/php/etc/php.ini
extension=amqp.so
重启php-fpm
/etc/init.d/php-fpm restart
查看amqp扩展是否安装成功
[root@localhost ~]# php -m | grep amqp
amqp
测试php访问amqp
admin用户是我在上一节安装介绍添加的,当然也可以直接使用guest进行连接。
<?php
$config = [
'host' => '127.0.0.1',
'vhost' => '/',
'port' => 5672,
'login' => 'admin',
'password' => '123456'
];
$con = new \AMQPConnection();
if($con->connect()){
echo '连接成功';
}
然后访问连接成功
[root@localhost amqp]# php demo.php
连接成功
在实际项目中可以在https://packagist.org 查找amqp的库,这里推荐使用 php-amqplib
,可通过如下方法加载
composer require php-amqplib/php-amqplib