Select Page
IIS 主機上限制 ApplicationPool 記憶體的方法

IIS 主機上限制 ApplicationPool 記憶體的方法

最近遇到 PHP 太吃記憶體的問題,我除了在php.ini 中設定 limit memory 以外,也打算在 IIS 中把總量的記憶體限制住,避免讓主機的記憶體爆滿,而當機,可以在記憶題超過限制後,把自己行程回收。

設定方法

在管理介面中,找到 「Advanced Settings」 ,進去後往下滑找到 「Private Memory Limit (KB)」 ,這邊這個數值是 KB 為主,如果希望將 Private Memory Limit (KB) 設定為 10GB,您需要將其設定為 10485760 KB 設定公式如下

10 GB = 10 * 1024 * 1024 KB = 10485760 KB

我設定的邏輯是觀察主機上所有的 Application Pool 會用到多少的記憶體,然後去分配她

Redis提升WP性能:一步步教您如何優化安裝與配置Redis資料庫

Redis提升WP性能:一步步教您如何優化安裝與配置Redis資料庫

Redis作為一款開源的高性能key-value數據庫,已經在眾多頂尖科技公司和網站獲得廣泛應用。本文將引領您走過安裝和配置Redis資料庫的過程,並提供實用的優化技巧,助力您的系統性能達到新的高峰。

為什麼選擇Redis?

首先,讓我們理解一下為什麼您應該選擇Redis。Redis以其極速性能、靈活的數據結構和高可用性成為獨一無二的選擇。它可以作為緩存,消息佇列,以及在高壓情況下用作可靠的數據存儲。

安裝Redis

Ubuntu安裝Redis

sudo apt install redis-server

Windows 安裝 Redis

直接下載微軟製作的安裝包,下載網址 https://github.com/MicrosoftArchive/redis/releases

驗證Redis是否安裝成功

如果是剛安裝好,並且在同一台機器上可以直接打指令 redis-cli 就可以連線

redis-cli
redis-cli ping
redis-cli info

如果是別台機器的話,記得要開防火牆,並且指定 IP 以及指定 Port 和指定密碼

redis-cli -h 192.168.0.X -p 6379 -a 123456

設定Redis

設定檔案通常位於 /etc/redis/redis.conf ,編輯完記得要重開服務 sudo systemctl restart redis ,不確定conf檔案的位置的話,可以用 redis-cli info 查找,會顯示以下資訊

executable:/usr/bin/redis-server
config_file:/etc/redis/redis.conf

sudo nano /etc/redis/redis.conf
  • bind:若要遠端連入Redis伺服器,就會需要設定 bind 0.0.0.0 ::
  • databases:設定可用的資料庫數量,在索引的時候是從0開始數,預設會使用索引值為0的資料庫。這個項目的預設值是16
  • save:設定在一定的間隔時間內若資料庫有發生一定程度的改變,就將記憶體中當下的資料存成檔案(快照)。save的撰寫格式為save <seconds> <changes>save 60 10000表示在60秒內至少有10000個key被改變則做一次快照。
  • requirepass:設定客戶端與Redis伺服器連線時所需要的密碼。預設沒有設定,表示不啟用密碼驗證功能。
  • maxclients:設定最大連線數。預設沒有設定,當作10000
  • maxmemory:設定最大的記憶體使用量,如果記憶體用量達到限制,就會根據maxmemory-policy項目設定的策略來嘗試移除key,如果無法移除,就會使該次插入或修改的操作回傳錯誤。預設沒有設定,表示不限制。
  • maxmemory-policy:記憶體用量達到限制時採取的策略。預設沒有設定,當作noeviction,不移除key。其它策略如下:
    • volatile-lru:根據LRU演算法移除過期的key。
    • allkeys-lru:根據LRU演算法移除key。(不管有沒有過期)
    • volatile-lfu:根據LFU演算法移除過期的key。
    • allkeys-lfu:根據LFU演算法移除key。(不管有沒有過期)
    • volatile-random:隨機移除過期的key。
    • allkeys-random:隨機移除key。(不管有沒有過期)
    • volatile-ttl:移除已過期的key中,TTL最小的key。
#bind 127.0.0.1 ::1
bind 0.0.0.0 ::

重啟服務

sudo systemctl restart redis

清除Redis的資料

利用 redis-cli 進去 Redis 主機後,輸入

flushall

清除單一資料的指令是

flush db0

在 WordPress 中使用 Redis

Redis Object Cache 外掛網址 https://wordpress.org/plugins/redis-cache/

設定 wp-config.php

// adjust Redis host and port if necessary 
define( 'WP_REDIS_HOST', '127.0.0.1' );
define( 'WP_REDIS_PORT', 6379 );

// change the prefix and database for each site to avoid cache data collisions
define( 'WP_REDIS_PREFIX', 'my-moms-site' );
define( 'WP_REDIS_DATABASE', 0 ); // 0-15

// reasonable connection and read+write timeouts
define( 'WP_REDIS_TIMEOUT', 1 );
define( 'WP_REDIS_READ_TIMEOUT', 1 );

/* That's all, stop editing! Happy publishing. */
require_once(ABSPATH . 'wp-settings.php');

組態檔

Configuration constantDefaultDescription
WP_REDIS_HOST127.0.0.1The hostname of the Redis server
WP_REDIS_PORT6379The port of the Redis server
WP_REDIS_PATHThe path to the unix socket of the Redis server
WP_REDIS_SCHEMEtcpThe scheme used to connect: tcp or unix
WP_REDIS_DATABASE0The database used by the cache: 0-15
WP_REDIS_PREFIXThe prefix used for all cache keys to avoid data collisions, replaces WP_CACHE_KEY_SALT. Should be human readable, not a “salt”.
WP_REDIS_PASSWORDThe password of the Redis server. Supports Redis ACLs arrays: ['user', 'password']
WP_REDIS_MAXTTL0The maximum time-to-live of cache keys
WP_REDIS_CLIENTThe client used to communicate with Redis: predisphpredis or relay
WP_REDIS_TIMEOUT1The connection timeout in seconds
WP_REDIS_READ_TIMEOUT1The timeout in seconds when reading/writing
WP_REDIS_IGNORED_GROUPS[]Groups that should not be cached between requests in Redis

常用控制指令

CommandDescription
wp redis statusShows the object cache status and diagnostics
wp redis enableEnables the object cache
wp redis disableDisables the object cache
wp redis update-dropinUpdates the object cache drop-in

效能考量,安裝 Phpredis

請先到 phpredis 這邊搜尋對應你平台的檔案,用 Linux Ubuntu 為例,下載 redis-6.0.2 版本 ,並且解壓縮他

wget https://pecl.php.net/get/redis-6.0.2.tgz
tar -zxvf redis-6.0.2.tgz
cd redis-6.0.2

接下來先編譯原檔案

sudo phpize
sudo ./configure
sudo make && sudo make install

完成編譯檔案後,要把 .so 檔案放到 php 的 modules 中,先把該目錄找出來

php -i | grep extension_dir

系統回應我,extension_dir => /usr/lib/php/20220829 => /usr/lib/php/20220829 ,則將剛編譯好,放在 modules 下的 redis.so 複製到正確的目錄中

sudo cp ./modules/redis.so /usr/lib/php/20220829/

複製完畢後,需要去修改 php.ini 檔案,讓他支援 redis,這邊我示範用 Nginx

sudo nano /etc/php/8.2/fpm/php.ini

將 extension 打開,請找到 Dynamic Extensions ,並且在下面加入

extension=redis

設定完成後,重開 php 讓他生效

sudo systemctl restart php8.2-fpm

檢查方法,利用info.php,並且搜尋是否有redis字眼,如下圖就是成功了

關於Redis的大小事

預設安裝完畢,初始話是支援16個資料庫的,分別由編號 0-15 ,要增加資料庫,要去 Redis 的組態檔裡面修改 redis/redis.conf 中,找到 databases ,並且調整數值後,重新啟動即可

databases 16

Redis 讀取資料

redis-cli set my_key "Value"
redis-cli get my_key

Redis 列出所有的 KEY

redis-cli KEYS *

相關文章

詳細的指令操作介紹

HTML vdieo 自動播放功能無法在 iOS (Safari) 中正常運行

如果要在 HTML 中播放影片,並且當作背景,一進來就自動播放,通常我們使用 video tag ,可以參考 https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/video ,通常長得像是

<video autoplay poster="posterimage.jpg">
   <source src="video.mp4" type="video/mp4">
</video>

其中如果你要正常在各個瀏覽器中正常的「自動播放」,要加入 muted ,因為現在的瀏覽器的安全規範,都是只能自動播放無音軌的影片

<video autoplay muted poster="posterimage.jpg">
   <source src="video.mp4" type="video/mp4">
</video>

那很多人會發現,ios 上面的設備有問題,因為在 ios 上面還有自己的規範,https://developer.apple.com/documentation/webkit/delivering_video_content_for_safari#3030250 ,主要就是講要加入 playsinline 屬性來定義影片的行為

<video autoplay muted playsinline poster="posterimage.jpg">
   <source src="video.mp4" type="video/mp4">
</video>

到此為止就都可以正常在各個設備上使用

Windows server IIS PHP Curl SSL Certificate 錯誤修正

Windows server IIS PHP Curl SSL Certificate 錯誤修正

WordPress 最好還是安裝在 Linux 下比較少問題,但非得要用到 Windows IIS 的時候,要注意現在 php 程式設計師很喜歡用 curl 在讀取資料,當你用 curl 讀取 SSL 加密(現在還有那個網站沒有)的時候,應該是會收到 PHP Curl SSL Certificate Problem: Unable to get local issuer certificate 錯誤訊息,解決方法如下

下載 pem 檔案

https://curl.se/docs/caextract.html

https://curl.se/ca/cacert.pem

將檔案放在 php 下的 SSL 目錄中

copy cacert.pem C:\php8\extras\ssl\

修改 php.ini

打開 php.ini 找到 curl.cainfo = ,加入你 cacert.pem 的路徑

重新啟動 IIS

1.回收 Application Pools

2.重啟網站

之後就可以使用了

Windows IIS Server (2022) 安裝 PHP 的方法以及設定

Windows IIS Server (2022) 安裝 PHP 的方法以及設定

我用 Windows Server 2022,已經沒法用Microsoft® Web Platform Installer (Web PI) 了,所以我就純手動安裝 PHP 8,這篇文章會假設你已經安裝好 IIS 了,並且提供下載PHP,安裝PHP,設定PHP,調教PHP,加速PHP等功能去說明

下載 Windows 版本的 PHP

https://www.php.net/downloads.php

在上面的畫面中選擇 Windows downloads,我們採用的是 IIS 所以在下面的畫面中選擇下載 Non Thread Safe 的 zip

下載完畢後,自行建立一個目錄把ZIP解壓縮後放在該目錄下,我是安裝了多個 PHP 版本,所以我建立了 PHP8 的目錄

C:\php8

Windows Server 主機啟用 FastCGI

[> 伺服器管理員]> [新增角色服務],在 [應用程式開發] 底下,選取 [CGI] 核取方塊

修改 PHP 組態的設定 (php.ini)

修改 C:\php8\php.ini ,將設定改成 Windows Server 適用的參數,官方建立設定如下

;IS 下的 FastCGI 支援模擬呼叫方用戶端之安全性權杖的能力。 這可讓 IIS 定義要求執行的安全性內容。
fastcgi.impersonate = 1

cgi.force_redirect = 0

;這可讓 PHP 遵循 CGI 規格存取實際路徑資訊。 IIS FastCGI 實作需要這個延伸模組設定。
cgi.fix_pathinfo = 1

;將 extension_dir 設定為指向 PHP 延伸模組所在的位置
extension_dir = "./ext"

我個人常用的設定如下

max_execution_time = 300

memory_limit = 256M

upload_max_filesize = 10M
post_max_size = 10M

log_errors = On
error_log = syslog

default_socket_timeout = 300

extension=curl
extension=fileinfo
extension=gd
extension=intl
extension=mbstring
extension=exif      ; Must be after mbstring as it depends on it
extension=mysqli
extension=openssl
extension=pdo_mysql
extension=php_imagick.dll

[opcache]
; Determines if Zend OPCache is enabled
opcache.enable=1

; Determines if Zend OPCache is enabled for the CLI version of PHP
opcache.enable_cli=1

; The OPcache shared memory storage size.
opcache.memory_consumption=256

; The amount of memory for interned strings in Mbytes.
opcache.interned_strings_buffer=8

; The maximum number of keys (scripts) in the OPcache hash table.
; Only numbers between 200 and 1000000 are allowed.
opcache.max_accelerated_files=4000

; The maximum percentage of "wasted" memory until a restart is scheduled.
;opcache.max_wasted_percentage=5

; When this directive is enabled, the OPcache appends the current working
; directory to the script key, thus eliminating possible collisions between
; files with the same name (basename). Disabling the directive improves
; performance, but may break existing applications.
;opcache.use_cwd=1

; When disabled, you must reset the OPcache manually or restart the
; webserver for changes to the filesystem to take effect.
opcache.validate_timestamps=1

; How often (in seconds) to check file timestamps for changes to the shared
; memory storage allocation. ("1" means validate once per second, but only
; once per request. "0" means always validate)
opcache.revalidate_freq=2

; Enables or disables file search in include_path optimization
;opcache.revalidate_path=0

; If disabled, all PHPDoc comments are dropped from the code to reduce the
; size of the optimized code.
;opcache.save_comments=1

; If enabled, compilation warnings (including notices and deprecations) will
; be recorded and replayed each time a file is included. Otherwise, compilation
; warnings will only be emitted when the file is first cached.
;opcache.record_warnings=0

; Allow file existence override (file_exists, etc.) performance feature.
;opcache.enable_file_override=0

; A bitmask, where each bit enables or disables the appropriate OPcache
; passes
;opcache.optimization_level=0x7FFFBFFF

;opcache.dups_fix=0

; The location of the OPcache blacklist file (wildcards allowed).
; Each OPcache blacklist file is a text file that holds the names of files
; that should not be accelerated. The file format is to add each filename
; to a new line. The filename may be a full path or just a file prefix
; (i.e., /var/www/x  blacklists all the files and directories in /var/www
; that start with 'x'). Line starting with a ; are ignored (comments).
;opcache.blacklist_filename=

; Allows exclusion of large files from being cached. By default all files
; are cached.
opcache.max_file_size=0

; Check the cache checksum each N requests.
; The default value of "0" means that the checks are disabled.
;opcache.consistency_checks=0

; How long to wait (in seconds) for a scheduled restart to begin if the cache
; is not being accessed.
;opcache.force_restart_timeout=180

; OPcache error_log file name. Empty string assumes "stderr".
;opcache.error_log=

; All OPcache errors go to the Web server log.
; By default, only fatal errors (level 0) or errors (level 1) are logged.
; You can also enable warnings (level 2), info messages (level 3) or
; debug messages (level 4).
;opcache.log_verbosity_level=1

; Preferred Shared Memory back-end. Leave empty and let the system decide.
;opcache.preferred_memory_model=

; Protect the shared memory from unexpected writing during script execution.
; Useful for internal debugging only.
;opcache.protect_memory=0

; Allows calling OPcache API functions only from PHP scripts which path is
; started from specified string. The default "" means no restriction
;opcache.restrict_api=

; Mapping base of shared memory segments (for Windows only). All the PHP
; processes have to map shared memory into the same address space. This
; directive allows to manually fix the "Unable to reattach to base address"
; errors.
;opcache.mmap_base=

; Facilitates multiple OPcache instances per user (for Windows only). All PHP
; processes with the same cache ID and user share an OPcache instance.
;opcache.cache_id=

; Enables and sets the second level cache directory.
; It should improve performance when SHM memory is full, at server restart or
; SHM reset. The default "" disables file based caching.
;opcache.file_cache=

; Enables or disables opcode caching in shared memory.
;opcache.file_cache_only=0

; Enables or disables checksum validation when script loaded from file cache.
;opcache.file_cache_consistency_checks=1

; Implies opcache.file_cache_only=1 for a certain process that failed to
; reattach to the shared memory (for Windows only). Explicitly enabled file
; cache is required.
;opcache.file_cache_fallback=1

; Enables or disables copying of PHP code (text segment) into HUGE PAGES.
; Under certain circumstances (if only a single global PHP process is
; started from which all others fork), this can increase performance
; by a tiny amount because TLB misses are reduced.  On the other hand, this
; delays PHP startup, increases memory usage and degrades performance
; under memory pressure - use with care.
; Requires appropriate OS configuration.
;opcache.huge_code_pages=0

; Validate cached file permissions.
;opcache.validate_permission=0

; Prevent name collisions in chroot'ed environment.
;opcache.validate_root=0

; If specified, it produces opcode dumps for debugging different stages of
; optimizations.
;opcache.opt_debug_level=0

; Specifies a PHP script that is going to be compiled and executed at server
; start-up.
; https://php.net/opcache.preload
;opcache.preload=

; Preloading code as root is not allowed for security reasons. This directive
; facilitates to let the preloading to be run as another user.
; https://php.net/opcache.preload_user
;opcache.preload_user=

; Prevents caching files that are less than this number of seconds old. It
; protects from caching of incompletely updated files. In case all file updates
; on your site are atomic, you may increase performance by setting it to "0".
;opcache.file_update_protection=2

; Absolute path used to store shared lockfiles (for *nix only).
;opcache.lockfile_path=/tmp

要注意的延伸模組

  • 資料庫延伸模組(php_mysql) — 大部分開放原始碼應用程式會針對資料庫引擎使用 MySQL,請使用 php_mysql 或 php_mysqli 延伸模組。 針對新的開發工作,這些延伸模組都能正常運作,或考慮使用 MySQL 驅動程式的 PDO 版本 (PDO 是 PHP 擴充功能,可提供資料存取抽象層,可與各種資料庫搭配使用) ;這個額外的抽象層提供一組更豐富的物件資料庫功能和控制項。 如果 Microsoft® SQL Server ® (或快速版本,例如 Microsoft SQL Server 2008 Express 或 Microsoft®® SQL Server ® ® 2005 Express Edition) 是資料庫引擎,請使用開放原始碼應用程式的php_mssql擴充功能。 針對新的開發工作,請使用 SQL 驅動程式的 PDO 版本。
  • 影像處理延伸模組(imagick) — 許多可讓映射使用 GD2 擴充功能的開放原始碼應用程式 – php_gd2,其具有許多良好的基本映射操作應用程式開發介面, (API) 。 某些應用程式會使用 ImageMagick 應用程式和程式庫。 另外還有一個 php_exif 程式庫,可用來處理新式數位相機儲存在影像中的擴充資訊。
  • 國際化和當地語系化延伸模組– i18n 和 l10n 最常使用的兩個延伸模組是php_mbstring (多位元組字元串) 和php_gettext (原生語言支援) 。 許多開放原始碼應用程式都使用其中一個或兩者。
  • Web 服務延伸模組 – 根據所需的服務選擇 Web 服務延伸模組。 以 PHP 來說,會廣泛使用 SOAP 延伸模組。 XML-RPC 擴充功能通常與 SOAP 和其他服務搭配使用。

將 PHP 目錄加入環境變數中

IIS管理員中的設定

在管理員中找到「處理常式對應」

新增PHP對應

FastCGI PHP 對應參數

  • 要求路徑: *.php
  • 模組 :FastCGImodule
  • 可執行檔: C:\php8\php-cgi.exe
  • 名稱: FastCGI

參考資料

https://learn.microsoft.com/zh-tw/iis/application-frameworks/install-and-configure-php-on-iis/enable-fastcgi-support-in-iis-7-on-windows-server-2008-windows-server-2008-r2-windows-vista-or-windows-7?source=recommendations

https://learn.microsoft.com/zh-tw/iis/application-frameworks/install-and-configure-php-on-iis/install-and-configure-php?source=recommendations

http://www.imagemagick.org/script/index.php

使用 jQuery 移動元素(Div)

常常有需求要事後調整前台的畫面,尤其現在前端 javascript 的框架一大堆,只能事後處理,把元素的位置變來變去,我這邊舉利用 div 來代表,如何把元素變換位置,讓排版更簡單且容易些。

先準備有原來的 div

<div id="source">
  ....
</div>

想要把原來的Div移動到目的地的div,id 訂為 dest

<div id="dest">
  ....
</div>

JQuery 程式碼 appendTo(),把 div 移動到目的地 div 的裡面

$("#source").appendTo("#dest");

除了 appendTo() 最常用,還整理幾個常用的寫法,放在下面

$("#source").insertBefore("#dest");
$("#source").insertAfter("#dest");
$("#source").prependTo("#dest");
$("#source").appendTo("#dest");

參考資料

https://stackoverflow.com/questions/1279957/how-to-move-an-element-into-another-element