簡介
由于公司項目的發展,現在有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個容器信息表示部署成功
成功后訪問 http://127.0.0.1:8500/ui/
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}