由于公司项目的发展,现在有SaaS架构的B2B、B2C项目,且项目提供的功能多而杂;并且有大部分功能是重复的。虽然,并发不大,但是从维护和开发的角度讲,开发和维护一套的成本要小很多;所以自己在业余时间探索php的微服务架构。
基础知识普及:
1、hyerf:https://hyperf.wiki/2.0/#/
2、consul:https://www.consul.io/
3、swoole:https://wiki.swoole.com/#/
4、Docker:https://www.runoob.com/docker/docker-tutorial.html
5、docker-compose:https://www.runoob.com/docker/docker-compose.html
本文基于文章 《如何搭建PHP 微服务集群》 部署
"centos": ">=7.2"
"php": ">=7.2"
"hyperf": "=2.0"
"docker": "=19.03.13"
"docker-compose": "=1.27.4"
"swoole": "=4.2"
"Consul": "=1.8.6"
1、安装PHP7.2w
yum -y remove php*
rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
yum -y install php72w php72w-cli php72w-common php72w-devel php72w-embedded php72w-fpm php72w-gd php72w-mbstring php72w-MySQLnd php72w-opcache php72w-pdo php72w-xml
2、pear安装swoole
yum install php72w-pear
yum install php72w-devel
pecl install swoole
修改 php.ini 配置文件
extension=swoole.so
3、 安装composer
# 下载composer.phar
curl -sS https://getcomposer.org/installer | php
# 把composer.phar移动到环境下让其变成可执行
mv composer.phar /usr/local/bin/composer
# 测试
composer -V
# 输出:Composer version 2.0.7 2020-11-13 17:31:06
4、安装php-microservice-demo
git clone https://github.com/xugj-gits/php-microservice-demo.git
分别进入microservice-1、microservice-2、App目录执行:
composer install
5、安装Docker、Docker Compose
curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
# 启动Docker
sudo systemctl start docker
6、安装Docker Compose
sudo curl -L "https://github.com/docker/compose/releases/download/1.27.4/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
测试是否安装成功:
docker-compose --version
输出:docker-compose version 1.27.4, build unknown
7、启动Docker
在目录/root/php-microservice-demo/下执行:
docker-compose up
输出如下内容表示部署成功:
Starting consul-server-leader ... done
Starting microservice-1 ... done
Starting microservice-2 ... done
Starting app ... done
或者输入:
docker ps
出现4个容器信息表示部署成功
1、访问add接口:
curl http://127.0.0.1:9501/add?a=6&b=7
返回:{"a":6,"b":7,"add":13}
2、访问add接口:
curl http://127.0.0.1:9501/multiply?a=6&b=7
返回:{"a":6,"b":7,"multiply":42}