H5直播站点运维笔记二 Laravel 框架

H5直播站点运维笔记二 Laravel 框架

  • Laravel 框架篇
    • 一、PHP
      • 1. 查看PHP信息
      • 2. 运行管理
      • 3. FPM Configuration主要配置
    • 二、Composer依赖管理
      • 1.功能
      • 2.使用
    • 三、部署Laravel
      • 1.创建Laravel应用项目
      • 2.Laravel项目文件执行权限
      • 3.artisan命令行工具
      • 4.自定义功能加载配置
    • 四、任务定时器
      • 1.crontab定时器
      • 2.编辑定时器
      • 3.定时器参数
      • 4.特殊符号
      • 5.重启定时器任务
    • 五、性能优化
      • 1.PHP优化
        • (1)开启opcache内存预编译缓存代码
        • (2)Php-fpm优化
      • 2.Laravel优化
        • (1)配置信息缓存
        • (2)路由缓存
        • (3)类映射加载优化
        • (4)自动加载优化
        • (5)优化前后压力测试对比
  • 服务器篇
    • ...详见运维笔记 [《服务器篇》](https://blog.csdn.net/fuweipeng2012/article/details/113802140)
  • 数据库篇
    • ...详见运维笔记 [《数据库篇》](https://blog.csdn.net/fuweipeng2012/article/details/113805339)
  • 压测篇
    • ...详见运维笔记 [《压测篇》](https://blog.csdn.net/fuweipeng2012/article/details/113808399)

Laravel 框架篇

一、PHP

使用版本PHP 7.3.15

1. 查看PHP信息

(1)查看PHP版本
php -v

[root@VM-0-15-centos ~]# php -v
PHP 7.3.15 (cli) (built: Mar  2 2020 17:53:06) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.15, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.3.15, Copyright (c) 1999-2018, by Zend Technologies

(2)查看PHP运行情况
ps aux | grep php

[root@VM-0-15-centos ~]# ps aux |  grep php
root      1553  0.0  0.0 352512  6768 ?        Ss   Feb13   0:01 php-fpm: master process (/usr/local/php/etc/php-fpm.conf)                                                                    
www       1554  0.0  0.3 375608 31612 ?        S    Feb13   0:00 php-fpm: pool www                                                                                                            
www       1555  0.0  0.3 357380 25668 ?        S    Feb13   0:00 php-fpm: pool www                                                                                                            
www       1556  0.0  0.3 371596 27348 ?        S    Feb13   0:00 php-fpm: pool www                                                                                                            
www       1557  0.0  0.3 375616 31912 ?        S    Feb13   0:00 php-fpm: pool www                                                                                                            
www       1558  0.0  0.3 374128 27976 ?        S    Feb13   0:00 php-fpm: pool www                                                                                                            
www       1559  0.0  0.3 374068 30060 ?        S    Feb13   0:00 php-fpm: pool www                                                                                                            
www       1560  0.0  0.3 372176 28312 ?        S    Feb13   0:00 php-fpm: pool www                                                                                                            
www       1561  0.0  0.3 374128 28584 ?        S    Feb13   0:00 php-fpm: pool www                                                                                                            
root     13886  0.0  0.0 103328   852 pts/0    S+   00:06   0:00 grep php

(3)查看安装的PHP扩展模块
php -m
(4)php.ini文件的位置
php --ini

[root@VM-0-15-centos /]# php --ini
Configuration File (php.ini) Path: /usr/local/php/etc
Loaded Configuration File:         /usr/local/php/etc/php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)

2. 运行管理

(1)启动

  • CentOS/RHEL 6.x等旧版本
    service php-fpm start
[root@VM-0-15-centos /]# service php-fpm start
Starting php-fpm  done
  • CentOS/RHEL 7
    systemctl start php-fpm

(2)停止
service php-fpm stop
(3)重启
service php-fpm restart
(4)重载
service php-fpm reload

3. FPM Configuration主要配置

编辑php-fpm.conf配置文件
vi /usr/local/php/etc/php-fpm.conf

[global]
pid = run/php-fpm.pid
error_log = log/php-fpm.log
log_level = notice
#错误级别. 可用级别为: alert(必须立即处理), error(错误情况), warning(警告情况), notice(一般重要信息), debug(调试信息). 默认: notice.
rlimit_files = 65535
#设置核心rlimit最大限制值.
[www]
user = live
group = live
listen = 127.0.0.1:9000
#fpm监听端口,即nginx中php处理的地址
listen.backlog = 2048
#backlog数,-1表示无限制,由操作系统决定,此行注释掉就行。
pm = dynamic
pm.max_children = 1024
#子进程最大数
#设置”max_children”也需要根据服务器的性能进行设定,一台服务器正常情况下每一个php-cgi所耗费的内存在20M左右,因 此我的”max_children”我设置成40个,20M*40=800M也就是说在峰值的时候所有PHP-CGI所耗内存在800M以内,低于我的有 效内存1Gb。而如果我的”max_children”设置的较小,比如5-10个,那么php-cgi就会“很累”,处理速度也很慢,等待的时间也较 长。如果长时间没有得到处理的请求就会出现504 Gateway Time-out这个错误,而正在处理的很累的那几个php-cgi如果遇到了问题就会出现502 Bad gateway这个错误。
pm.start_servers = 10
#控制服务启动时创建的进程数
pm.min_spare_servers = 10
#保证空闲进程数最小值,如果空闲进程小于此值,则创建新的子进程
pm.max_spare_servers = 60
#保证空闲进程数最大值,如果空闲进程大于此值,此进行清理
pm.max_requests = 512
#设置每个子进程重生之前服务的请求数. 对于可能存在内存泄漏的第三方模块来说是非常有用的. 如果设置为 ‘0’ 则一直接受请求. 等同于 PHP_FCGI_MAX_REQUESTS 环境变量. 默认值: 0.
request_terminate_timeout = 10s
#设置单个请求的超时中止时间. 该选项可能会对php.ini设置中的’max_execution_time’因为某些特殊原因没有中止运行的脚本有用. 设置为 ‘0’ 表示 ‘Off’.当经常出现502错误时可以尝试更改此选项。
request_slowlog_timeout = 10s
#当一个请求该设置的超时时间后,就会将对应的PHP调用堆栈信息完整写入到慢日志中. 设置为 ‘0’ 表示 ‘Off’
slowlog = var/log/$pool.log.slow
#慢请求的记录日志,配合request_slowlog_timeout使用
#nginx会直接把 请求转交给php-fpm,而php-fpm再分配php-cgi进程来处理相关的请求,之后再依次返回,最后由nginx把结果反馈给客户端浏览器

二、Composer依赖管理

1.功能

Composer 是 PHP的一个依赖管理工具。我们可以在项目中声明所依赖的外部工具库,Composer 会帮你安装这些依赖的库文件,有了它,我们就可以很轻松的使用一个命令将其他人的优秀代码引用到我们的项目中来。
Composer 默认情况下不是全局安装,而是基于指定的项目的某个目录中(例如 vendor)进行安装。

2.使用

(1)列出项目所有已安装包

  • 进入laravel项目根目录,即compposer.json文件存在的目录
  • composer show命令
    composer show
    or
    /usr/local/bin/composer show //命令完整路径
    (2)更新包
  • 更新所有依赖
    composer update
  • 更新指定的包
    composer update monolog/monolog
  • 更新指定的多个包
    composer update monolog/monolog symfony/dependency-injection
  • 通配符匹配包
    composer update monolog/monolog symfony/*

三、部署Laravel

使用版本 Laravel Framework 6.18.1

1.创建Laravel应用项目

(1)方法1:composer create-project命令创建test_web项目,后面指定lararvel版本
composer create-project --prefer-dist laravel/laravel test_web 5.5.*
(2)方法2:安装全局laravel
/usr/local/bin/composer global require ” laravel/installer”

2.Laravel项目文件执行权限

(1)进入项目目录后
cd /home/myweb //按实际laravel项目存放路径
(2)添加文件执行权限,vendor目录、storage目录、bootstrap/cache目录
chmod -R 777 vendor/ storage/ bootstrap/cache/

3.artisan命令行工具

(1)全局laravel安装路径或laravel项目根目录存在artisan命令工具

[root@VM-0-15-centos bi]# ls
app      bootstrap      composer.lock  database      phpunit.xml  readme.md  routes      storage  webpack.mix.js
artisan  composer.json  config         package.json  public       resources  server.php  vendor

(2)常用命令
① 查看当前laravel的版本
php artisan --version

[root@VM-0-15-centos bi]# php artisan --version
Laravel Framework 6.18.1

② 列出所有可用命令
php artisan list

[root@VM-0-15-centos bi]# php artisan list
Laravel Framework 6.18.1

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
      --env[=ENV]       The environment the command should run under
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  MyIncreAds           广告投放pv/cv增量写入Mysql
  MyIncreBal           电子账户结算离线数据写入Mysql
  MyIncrePoint         用户积分增量&&邀请增量写入Mysql
  MyIncrePvuvvv        用户pv/uv/vv增量写入Mysql
  MyLogAds             广告投放日志写入Mysql
  MyLogPoint           用户积分日志写入Mysql
  MyLogVv              用户访问(Visit View)日志写入Mysql
  clear-compiled       Remove the compiled class file
  down                 Put the application into maintenance mode
  env                  Display the current framework environment
  help                 Displays help for a command
  list                 Lists commands
  migrate              Run the database migrations
  optimize             Cache the framework bootstrap files
  preset               Swap the front-end scaffolding for the application
  serve                Serve the application on the PHP development server
  tinker               Interact with your application
  up                   Bring the application out of maintenance mode
 auth
  auth:clear-resets    Flush expired password reset tokens
 cache
  cache:clear          Flush the application cache
  cache:forget         Remove an item from the cache
  cache:table          Create a migration for the cache database table
 config
  config:cache         Create a cache file for faster configuration loading
  config:clear         Remove the configuration cache file
 db
  db:seed              Seed the database with records
  db:wipe              Drop all tables, views, and types
 event
  event:cache          Discover and cache the application's events and listeners
  event:clear          Clear all cached events and listeners
  event:generate       Generate the missing events and listeners based on registration
  event:list           List the application's events and listeners
 key
  key:generate         Set the application key
 make
  make:channel         Create a new channel class
  make:command         Create a new Artisan command
  make:controller      Create a new controller class
  make:event           Create a new event class
  make:exception       Create a new custom exception class
  make:factory         Create a new model factory
  make:job             Create a new job class
  make:listener        Create a new event listener class
  make:mail            Create a new email class
  make:middleware      Create a new middleware class
  make:migration       Create a new migration file
  make:model           Create a new Eloquent model class
  make:notification    Create a new notification class
  make:observer        Create a new observer class
  make:policy          Create a new policy class
  make:provider        Create a new service provider class
  make:request         Create a new form request class
  make:resource        Create a new resource
  make:rule            Create a new validation rule
  make:seeder          Create a new seeder class
  make:test            Create a new test class
 migrate
  migrate:fresh        Drop all tables and re-run all migrations
  migrate:install      Create the migration repository
  migrate:refresh      Reset and re-run all migrations
  migrate:reset        Rollback all database migrations
  migrate:rollback     Rollback the last database migration
  migrate:status       Show the status of each migration
 notifications
  notifications:table  Create a migration for the notifications table
 optimize
  optimize:clear       Remove the cached bootstrap files
 package
  package:discover     Rebuild the cached package manifest
 queue
  queue:failed         List all of the failed queue jobs
  queue:failed-table   Create a migration for the failed queue jobs database table
  queue:flush          Flush all of the failed queue jobs
  queue:forget         Delete a failed queue job
  queue:listen         Listen to a given queue
  queue:restart        Restart queue worker daemons after their current job
  queue:retry          Retry a failed queue job
  queue:table          Create a migration for the queue jobs database table
  queue:work           Start processing jobs on the queue as a daemon
 route
  route:cache          Create a route cache file for faster route registration
  route:clear          Remove the route cache file
  route:list           List all registered routes
 schedule
  schedule:run         Run the scheduled commands
 session
  session:table        Create a migration for the session database table
 storage
  storage:link         Create a symbolic link from "public/storage" to "storage/app/public"
 vendor
  vendor:publish       Publish any publishable assets from vendor packages
 view
  view:cache           Compile all of the application's Blade templates
  view:clear           Clear all compiled view files

③ 查看某个命令的帮助
php artisan -h 命令
④ 新建控制器
php artisan make:controller PagesController

4.自定义功能加载配置

(1)在app/Http下建立myfunctions.php(根据自己的习惯命名),把函数写在这个文件里
(2)打开laravel项目根目录的conposer.json

"autoload": { 
...
"files": [
	"app/Http/Utility/myfunctions.php" //自定义函数文件
]
 },

(3)刷新自动加载配置项生效定义功能
composer dump-autoload

四、任务定时器

使用CentOS系统的Crontab定时器定时调度Laravel的schedule命令,实现定时任务模块运行。

1.crontab定时器

(1)-l 查询
(2)-e 编辑
(3)-r 删除

2.编辑定时器

crontab -e
* * * * * /usr/bin/php /home/web/bi/artisan schedule:run >> /dev/null 2>&1
:wq

3.定时器参数

(1)第一个“ * ” 一小时当中的第几分钟 0-59
(2)第二个“ * ” 一天当中的第几小时 0-23
(3)第三个“ * ” 一个月当中的第几天 1-31
(4)第四个“ * ” 一年当中的第几月 1-12
(5)第五个“ * ” 一周当中的星期几 0-7(0和7都代表星期日)

4.特殊符号

(1)* 代表任何时间。比如第一个“”就代表一小时中每分钟都执行一次的意思。
(2), 代表不连续的时间。比如“0 8,18 * * * 命令”,代表在每天的8点0分,18点0分都执行一次命令
(3)- 代表连续的时间范围。比如“0 7 * * 1-5命令”,代表在周一到周五的凌晨7点0分执行命令
(4)
/n 代表每隔多久执行一次。比如“*/10 * * * * 命令”,代表每隔10分钟就执行一遍命令

5.重启定时器任务

service crond restart

五、性能优化

1.PHP优化

(1)开启opcache内存预编译缓存代码
  • 统计项目中php文件数量
    find /home -type f -print | grep php | wc -l
  • 打开php.ini配置文件
  • 找到:[opcache] 配置栏
[opcache]
; 开关打开
opcache.enable=1
; 设置共享内存大小, 单位为:Mb
opcache.memory_consumption=128
;如果启用,那么 OPcache 会每隔 opcache.revalidate_freq 设定的秒数 检查脚本是否更	新。 如果禁用此选项,你必须使用 opcache_reset() 或者 opcache_invalidate() 函数来手动	重置 OPcache,也可以 通过重启 Web 服务器来使文件系统更改生效。
opcache.validate_timestamps=1
; 设置缓存过期时间(秒),到期后opcache检查代码是否改变编绎生成新的代码缓存
; 值为0表示每次请求都检查
;opcache.revalidate_freq=60
;添加opcache.so 主要作用是用来引用opcache
zend_extension="opcache.so"
zend_extension="/usr/local/php/lib/php/extensions/no-debug-non-zts-20180731/opcache.so"
;决定内存最多可以缓存php文件数,大于你的项目php文件总和
;统计项目中php文件数量find /home -type f -print | grep php | wc -l
;真实取值在质数集合{223,463,983,1979,3907,7963,16229,32531,65407,130987}
opcache.max_accelerated_files=16229
; 打开快速关闭, 打开这个在PHP Request Shutdown的时候回收内存的速度会提高
opcache.fast_shutdown=1
  • 重启php
    service php-fpm reload
  • 判断opcache是否启用
    php-fpm -m
[root@VM-0-15-centos bi]# php-fpm -m
[PHP Modules]
...常规模块
[Zend Modules]
Zend OPcache
  • 优化前后压力测试对比
    1)Abs
  • 优化前
    Requests per second: 13.33 [#/sec] (mean)
  • 优化后
    Requests per second: 77.13 [#/sec] (mean)
    2)Abs过程postman单次请求
  • 优化前
    Time:36.76s size:4.98KB
  • 优化后
    Time:4.41s size:4.98KB
(2)Php-fpm优化
  • 打开php-fpm.conf配置文件
  • 优化进程数
    1)process.max =320
    //控制子进程最大数的全局变量, pm子进程数量的指令受到这个值的限制, 0表示无限制
    2)pm = dynamic
    //选项有static和dynamic。选择static,则由pm.max_children指定固定的子进程数。
    //如dynamic,由start_servers、min_spare_servers、max_spare_servers 决定
    //对于内存大的服务器(比如8G以上)来说,指定静态的max_children实际上更为妥当, 因为这样不需要进行额外的进程数目控制,会提高效率
    3)pm.max_children = 192
    //静态方式下同一时间最大的进程数,计算方式:内存/30M
    4)pm.start_servers = 16
    //php-fpm启动时开启的等待请求到来的进程数
    //默认值为:min_spare_servers + (max_spare_servers – min_spare_servers) / 2
    5)pm.min_spare_servers = 8
    //在空闲状态下,运行的最小进程数,如果小于此值,会创建新的进程
    6)pm.max_spare_servers = 256
    //动态方式下的最大php-fpm进程数量
  • 最大处理请求数
    pm.max_requests = 512
    //最大处理请求数是指一个php-fpm的worker进程在处理多少个请求后就终止掉,master进程会重新respawn一个新的。
    //这个配置的主要目的是避免php解释器或程序引用的第三方库造成的内存泄露
  • 最长执行时间
    request_terminate_timeout = 120
    //脚本执行超时时间,单位秒
  • Backlog请求积压
    1)listen.backlog = 4096
    #backlog数,-1表示无限制,由操作系统决定,php最大的backlog可以到2000
    #未accept处理的socket队列大小
    #其他平台默认65535,高并发时重要,合理设置会及时处理排队的请求;
    #太大会积压太多,处理完后nginx在前面都等超时断开和fpm的socket连接了
  • 主进程安全保护
    避免PHP-FPM主进程由于某些糟糕的PHP代码挂掉,需要设置重启的全局配置
    1)emergency_restart_threshold =20
    //错误进程数如果超过 emergency_restart_threshold个,php-fpm就会优雅重启
    2)emergency_restart_interval = 60s
    //表示在所设值内出现SIGSEGV或者SIGBUS错误的php-cgi,超过threshold时

2.Laravel优化

(1)配置信息缓存
  • php artisan config:cache
    //命令会生成文件 bootstrap/cache/config.php
    //配置信息缓存不会随着更新而自动重载,所以,开发时候建议关闭配置信息缓存,一般在生产环境中使用,可以配合 Envoy 任务运行器 一起使用
  • php artisan config:clear
    //此命令做的事情就是把 bootstrap/cache/config.php 文件删除
(2)路由缓存
  • php artisan route:cache
    //路由缓存可以有效的提高路由器的注册效率,在大型应用程序中效果越加明显
    //命令会生成 bootstrap/cache/routes.php 文件,需要注意的是,路由缓存不支持路由匿名函数编写逻辑
  • php artisan route:clear
    //清除路由缓存
(3)类映射加载优化
  • php artisan optimize --force
    //把常用加载的类合并到一个文件里,通过减少文件的加载,来提高运行效率
    //生成 bootstrap/cache/compiled.php 和 bootstrap/cache/services.json 两个文件
  • php artisan clear-compiled
    //清除类映射加载优化
(4)自动加载优化

composer dumpautoload -o
//此命令不止针对于 Laravel 程序,适用于所有使用 composer 来构建的程序。
//此命令会把 PSR-0 和 PSR-4 转换为一个类映射表,来提高类的加载速度。

(5)优化前后压力测试对比

1)Abs

  • 优化前
    Requests per second: 77.13 [#/sec] (mean)
  • 优化后
    Requests per second: 87.03 [#/sec] (mean)

2)abs过程postman单次请求

  • 优化前
    Time:4.41s size:4.98KB
  • 优化后
    Time1.033s size:4.98KB

本章完


服务器篇

…详见运维笔记 《服务器篇》

数据库篇

…详见运维笔记 《数据库篇》

压测篇

…详见运维笔记 《压测篇》

你可能感兴趣的:(运维,php,lavarel,运维)