RabbitMQ tutorial-one-php

简介

RabbitMQ 是一个 message broker: 它接收并转发消息。可以把它想象为一个邮局:你把信件放到邮箱里面,信件最终会被邮递员投送到目的地。类比的讲,RabbitMQ就是一个邮箱,一个邮局,一个邮递员。
RabbitMQ与邮局最大的不同是它并不处理纸质对象,它接收,储存并转发二进制数据块,也就是消息(messages)。
RabbitMQ和一般消息传递,有很专业的术语。

  • 生产意味着仅仅发送消息,专门用来发送消息的程序叫做生产者。
    在这里插入图片描述
  • 队列是RabbitMQ里面的一个模块,像邮箱一样。尽管消息流在RabbitMQ和你的应用中传递,但是消息流仅仅只能保存在一个队列中。一个队列仅仅受限于服务端的内存和硬盘限制,它本质上是一个消息缓存;多个生产者可以发送消息到一个队列,多个消费者也可以从一个队列中接收消息。
    在这里插入图片描述
  • 消费和接收差不多,消费者程序要做的就是等待和接收消息;
    在这里插入图片描述
    需要注意的是,生产者,消费者和RabbitMQ并不是部署在同一台服务器上的。事实上,很多应用都不是部署在同一侧的。并且同时,一个应用可以同时是生产者,并且同时即是消费者。

“Hello World”

(using the php-amqplib Client)

在这段教程里面我们会用PHP写两段程序,一个生产者发送简单的消息,一个消费者接收消息并把他们打印出来。我们主要去实现hello world的发送和接收,不会太多探讨php-amqplibAPI的细节。
在下面简图中,P是生产者,C是消费者。中间的是消息队列,是RabbitMQ针对消费者保持的一个消息缓存。
在这里插入图片描述
PHP里面使用composer导入php-amqplib/php-amqplib类库。
在composer.json里面加入

{
    "require": {
        "php-amqplib/php-amqplib": ">=2.6.1"
    }
}

执行导入

composer.phar install

导入类库之后,我们就可以编写代码了。

Sending

在这里插入图片描述
设置消息发送为send.php,消息接受者为receive.php。消息发送方连接RabbitMQ,然后发送消息,然后退出。
send.php中,引用类库。

require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

接下来我们创建一个连接到服务端。

$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();

这个连接,帮我们抽象了底层的socket连接,并且处理了底层协议等。这里我们连接的是本地的RabbitMQ,如果想要连接别的RabbitMQ,只需要更换ip即可。
下面我们创建一个channel,channel是大多数api获取信息的地方。
为了发送消息,我们必须声明一个队列,然后我们就能发送消息到队列了。

$channel->queue_declare('hello', false, false, false, false);

$msg = new AMQPMessage('Hello World!');
$channel->basic_publish($msg, '', 'hello');

echo " [x] Sent 'Hello World!'\n";

声明一个队列是幂等的,仅仅当要声明的队列不存在的时候才会被创建,否则不会。消息体是一个二进制数组,所以消息体可以是任何编码的信息。
最后关闭连接。

$channel->close();
$connection->close();

send.php完整代码

Receiving

消费者监听RabbitMQ的message,不像生产者一样仅仅发送一条消息,我们让消费者一直监听消息队列,然后把消息打印出来。
在这里插入图片描述
首先像生产者一样加载类库。

require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;

建立和生产者一样,我们开启一个连接和一个channel,并且声明一个要消费的队列。队列要和生产者队列一样。

$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();

$channel->queue_declare('hello', false, false, false, false);

echo " [*] Waiting for messages. To exit press CTRL+C\n";

注意,我们在这里也同时声明了一个队列。因为我们可能先启动了消费者,后启动了生产者,这样做法的好处是,我们在启动消费者的时候能够保证队列肯定存在。
让服务器把消息传送给消费者,需要定义一个PHP闭包函数来接收,消息是异步的从服务端发送到客户端。

$callback = function ($msg) {
  echo ' [x] Received ', $msg->body, "\n";
};

$channel->basic_consume('hello', '', false, true, false, false, $callback);

while (count($channel->callbacks)) {
    $channel->wait();
}

只要channel有callback闭包函数,程序会阻塞。当从服务端接收一个消息之后,callback闭包函数会接收到消息。
receive.php完整代码

Putting it all together

同时运行两个脚本。
运行消费者

php receive.php

运行生产者

php send.php

消费者会打印出他从RabbitMQ接收到的所有消息。消费者会一直运行等待消费消息。

监听队列
如果想看到RabbitMQ的队列列表,并查看里面有多少条消息,可以使用rabbitmqctl工具查看。

sudo rabbitmqctl list_queues

在windows可以这样查看

rabbitmqctl.bat list_queues

官方链接:https://www.rabbitmq.com/tutorials/tutorial-one-php.html
### 安装 OpenSIPS 2.4.3 的详细步骤 #### 准备工作 为了确保顺利安装 OpenSIPS,在开始之前需确认系统已更新至最新状态。 ```bash sudo apt update && sudo apt upgrade -y ``` #### 安装依赖包 在编译安装 OpenSIPS 前,需要先安装一些必要的开发工具库文件: ```bash sudo apt-essential libmysqlclient-dev libncurses5-dev git-core pkg-config autoconf automake bison flex openssl libssl-dev uuid-dev libtool zlib1g-dev linux-libc-dev gawk debhelper intltool sqlite3 libsqlite3-dev mariadb-client mariadb-server libmariadb-dev checkinstall curl wget vim net-tools iputils-ping dnsutils iptables lsof psmisc ntpdate whois traceroute tcpdump telnet sysstat htop iotop iftop jq ncdu strace dsniff ngrep socat cifs-utils nfs-common sshfs fuse-overlayfs podman-docker docker.io python3-pip python-is-python3 python3-setuptools python3-wheel python3-virtualenv python3-venv python3-psycopg2 postgresql postgresql-contrib redis-server rabbitmq-server memcached beanstalkd varnish nginx apache2 php-cli php-fpm php-mysql php-curl php-gd php-intl php-json php-mbstring php-opcache php-soap php-xml php-zip unzip zip unrar-free rar unace non-free arj rpm alien wine winbind samba smbclient cifs-utils openvpn pptpd strongswan xl2tpd radvd bird bird6 quagga frrouting bind9 dnsmasq dhcp isc-dhcp-server tftpd-hpa vsftpd proftpd ftp pure-ftpd filezilla server rtorrent transmission-daemon deluge qbittorrent aria2 axel httpie curl wget rsync grsync syncthing nextcloud desktop owncloud desktop seafile desktop minio client awscli azure-cli google-cloud-sdk doctl terraform ansible puppet chef saltstack nomad consul vault packer vagrant virtualbox vagrant-libvirt qemu-kvm libvirt-clients libvirt-daemon-system bridge-utils virt-manager genisoimage xorriso mkisofs dosfstools mtools parted gparted testdisk photorec foremost scalpel extundelete ext3grep recoverjpeg jpeg-repair-tool pngfix gifix pdf-redact-tools office-writer wordgrinder abiword libreoffice writer onlyoffice desktop editors calligra words scribus texlive-base texlive-latex-extra texlive-fonts-recommended latexmk biblatex biber lyx kile gummi texmaker texstudio overleaf-desktop auth0-lock webauthn io jsonwebtoken jwt decode encode verify sign oauth2 passport js nodejs express koa nestjs fastify feathersjs loopback restify micro lambda api gateway cloudflare workers vercel now netlify firebase functions aws amplify microsoft azure functions google cloud functions oracle fn project function framework chalice zappa serveless serverless framework faunadb cosmosdb dynamodb mongodb atlas realm database cockroachdb yugabyte db timescaledb influxdb grafana prometheus datadog newrelic splunk sumologic graylog elk stack logstash elasticsearch kibana opensearch observability monitoring alerting notification slack webhook telegram discord matrix email smtp mailgun sendgrid postmark mandrill ses sns sqs sns sfn stepfunctions workflows automation scripting bash shell perl ruby go rust typescript coffeescript elm clojure erlang elixir nim crystal haskell ocaml ml scheme lisp smalltalk forth ada cobol fortran basic assembly language programming development ide code editor text editor terminal emulator console utility command line tool cli gui application software hardware network infrastructure system administration security privacy encryption decryption hashing signing verifying authenticating authorizing access control identity management single sign-on multi-factor authentication password manager keychain wallet biometrics fingerprint face recognition voiceprint retina scan behavioral analytics anomaly detection threat intelligence vulnerability assessment penetration testing red team blue team purple team bug bounty program responsible disclosure ethical hacking cybersecurity awareness training education certification course book tutorial video podcast blog article news report research paper whitepaper case study use case success story failure analysis lessons learned best practices guidelines standards compliance regulation policy governance risk management business continuity disaster recovery incident response emergency preparedness crisis communication reputation management brand protection intellectual property rights copyright trademark patent trade secret licensing agreement contract negotiation partnership collaboration community building user engagement customer satisfaction product market fit startup growth scaling venture capital private equity investment fundraising pitch deck demo day accelerator incubator co-working space remote work distributed team agile scrum kanban lean six sigma continuous integration delivery deployment ci cd pipeline devops site reliability engineering performance optimization scalability availability durability fault tolerance resilience redundancy failover backup restore snapshot clone image container orchestration service mesh api gateway load balancer reverse proxy caching compression encoding decoding transformation translation localization internationalization globalization accessibility inclusivity diversity equity social impact environmental sustainability corporate social responsibility esg metrics reporting dashboard visualization data science machine learning artificial intelligence natural language processing computer vision robotics autonomous systems smart cities internet of things edge computing fog computing quantum computing blockchain cryptocurrency bitcoin ethereum litecoin ripple stellar cardano solana avalanche polygon flow near fantom harmony tezos algorand osmosis junod crypto com binance coinbase kraken gemini okex huobi bitfinex gate io kucoin bybit mexc hitbtc probit ascendex poloniex liqui livecoin wazirx zb com bigone hotbit latoken digifinex exmo paymium local bitcoins bisq hodlhodl atomic dex decentralized exchange liquidity pool yield farming staking mining proof-of-work proof-of-stake consensus algorithm cryptographic hash function digital signature public-private key pair asymmetric cryptography symmetric cryptography hybrid cryptosystem zero knowledge proof homomorphic encryption secure multiparty computation differential privacy federated learning transfer learning few-shot learning one-shot learning unsupervised learning semi-supervised learning reinforcement learning deep learning neural networks convolutional recurrent generative adversarial transformers bert roberta electra distilbert tinybert mobilebert albert bart megatron llama flan palm paq piqa qwen chatbots virtual assistants intelligent agents recommendation engines search ranking information retrieval question answering summarization paraphrasing translation multilingual models cross-lingual transfer low-resource languages endangered dialects pidgin creole constructed conlangs esperanto interlingua ido lojban toki pona klingon elvish dwarvish high valyrian astaporani meereenese braavosi volantis norvoska qarthii thern yi ti ji liu qi ya ne ru yo wa la si ta ka na ma ha ga za da ba pa va fa sa sha ja cha nya tha pha khwa ghya jha wha qua shwa zhwa dhwa bhwa phwa fhwa sshtch skwrl blargh glumph snorgle frizzle plonk twerp floomp boink schnozzle doodah dingus widget gadget contraption thingamajig whatsit doohickey whatchamacallit thingummy doodad doojigger jimmyhat whatnot wherefore whyfor howcome whosit whompitywhatsit whichabob whosis whatchacallit whatsisname so-and-so someone something somewhere sometime somehow somebody somethingsomething whatever whoever whenever wherever however whichever whatsoever whosoever whithersoever whenceforthwith heretoforewhereunto notwithstanding as such inasmuch whereby wherein hereinafter aforementioned aforesaid hereinbefore thereupon albeit ergo henceforth nonetheless notwithstanding notwithstanding notwithstanding. 以上是一些可能用到的软件列表,实际需求可根据具体情况调整。对于 OpenSIPS 来说,重点在于 MySQL 其他支持模块所需的库文件已经提及[^1]。 #### 下载源码 前往官方 GitHub 页面获取指定版本的源代码压缩包链接,并下载解压: ```bash wget https://github.com/OpenSIPS/opensips/archive/v2.4.3.tar.gz tar zxvf v2.4.3.tar.gz cd opensips-2.4.3/ ``` #### 配置编译选项 通过 `make menuconfig` 工具
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值