监测 MySQL 服务 挂掉自动重启

最近 MySQL 服务总是挂掉

cd ~
vim /mysqllisten.sh
#!/bin/bash
pgrep -x mysqld &> /dev/null
if [ $? -ne 0 ]
then
echo "MySQL stoped at time: `date` ">> /home/wwwlogs/mysql_messages
/etc/init.d/mysql restart
sleep 15s
MYSQLPORT=`netstat -na|grep "LISTEN"|grep "3306"|awk -F[:" "]+ '{print $4}'`
    if [ "$MYSQLPORT" == "3306" ]
then  
            echo "MySQL restart successful at time: `date` ">> /home/wwwlogs/mysql_messages   
        else
            echo "MySQL restart failed at time: `date` ">> /home/wwwlogs/mysql_messages 
            mail -s "wann! yourwebsitedomain's mysql restart failed" 这里写你的邮箱地址
        fi
else
echo "MySQL server is running"
fi
chmod +x ./mysqllisten.sh

添加定时任务

crontab -e

*/10 * * * * /bin/bash /root/mysqllisten.sh

service crond restart

LNMP使用中mysql宕机挂掉后自动重启脚本

http://xiaohost.com/1580.html

Swoole 编译报错 fatal error: hiredis/hiredis.h: No such file or directory

Swoole 当使用参数 –enable-async-redis 时编译报错

/tmp/pear/temp/swoole/swoole_redis.c:20:29: fatal error: hiredis/hiredis.h: No such file or directory

启用 Swoole 的 async-redis 扩展需要安装 hiredis,hiredis 需要 redis

安装 Redis

cd ~
wget http://download.redis.io/releases/redis-5.0.0.tar.gz
tar xzf redis-5.0.0.tar.gz
cd redis-5.0.0
make

安装 hiredis

cd ~
wget https://github.com/redis/hiredis/archive/v0.13.3.zip
unzip v0.13.3.zip
cd hiredis-0.13.3
make -j
sudo make install
sudo ldconfig
https://blog.liuguofeng.com/archives/3666

Swoole 编译错误 Enable http2 support, require nghttp2 library

安装 nghttp2

In file included from /tmp/pear/temp/swoole/swoole.c:16:0:
/tmp/pear/temp/swoole/php_swoole.h:142:2: error: #error "Enable http2 support, require nghttp2 library."
 #error "Enable http2 support, require nghttp2 library."

swoole 的 http2 模块依赖  nghttp2库,安装即可

wget https://github.com/nghttp2/nghttp2/releases/download/v1.30.0/nghttp2-1.30.0.tar.bz2 
tar -jxvf nghttp2-1.30.0.tar.bz2 
cd nghttp2-1.30.0 
./configure
make
make install

安装 PostgreSQL

如未安装报错如下:

configure: error: Cannot find libpq-fe.h. Please confirm the libpq or specify correct PostgreSQL(libpq) installation path
ERROR: `/tmp/pear/temp/swoole/configure --with-php-config=/usr/local/php/bin/php-config --enable-sockets=yes --enable-openssl=yes --enable-http2=yes --enable-mysqlnd=yes --enable-coroutine-postgresql=yes --enable-debug-log=yes' failed

解决办法

yum -y install postgresql-devel

PHP 使用 exec 搭配 MozJPEG 的一些心得

环境 CentOS 7 PHP 7.2.6

查看 php 所在用户与用户组

为 www:www

将 www 用户添加至 root 权限

visudo
## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL
www     ALL=(ALL) NOPASSWD: ALL

允许 root 用户执行任何命令在任何位置。NOPASSWD  后为执行哪些命令不用输入密码

reboot 重启系统

PHP 测试命令

echo exec('php -v',$a1,$b1);
dump($a1);dump($b1);

echo exec('sudo /opt/mozjpeg/bin/cjpeg -version',$a2,$b2);
dump($a2);dump($b2);

echo exec('sudo /opt/mozjpeg/bin/cjpeg -quality 60 -debug /home/wwwroot/hi.unetu.net/public/tmp/uploads/1.jpeg > /home/wwwroot/hi.unetu.net/public/uploads/1.jpeg',$a3,$b3);
dump($a3);dump($b3);

die();

返回结果

exec 中第三个参数为 0 表示执行成功,其他值如 1 表示失败,上述代码表示执行成功但第二和第三个命令没有返回值也没有输出值

其中第三条 mozjpeg/cjpeg 的压缩图片执行成功

如果想要返回值,查找了一下可以使用管道,在命令添加 2>&1,尝试如下

返回结果

第二条输出了语句,第二条和第三条也都执行成功,但第三条的图片损坏了无法预览

这和在命令行里使用相同命令执行的结果一致

其他尝试

第三条 MozJPEG 如果原图片损坏,则第三条返回 int(1),表示执行失败

参考文献

浅谈PHP的exec()函数无返回值排查方法

https://www.jb51.net/article/110108.htm

通过图像压缩优化降低网站页面大小

原文:通过图像压缩优化降低网站页面大小

http://www.jiajianhudong.com/article/56.html

How Image Optimization Decreased my Website’s Page Weight by 62%

https://medium.freecodecamp.org/image-optimization-558d9f449e3

图像是在网络上提供的最基本的内容类型之一。他们说一张图片胜过千言万语。但如果你不小心的话,它也可能值几兆。

因此,虽然网络图像需要清晰明快,但它们也必须以可管理的尺寸交付,以便加载时间保持很小并且数据使用保持在可接受的水平。

在我的网站上,我注意到我的主页的页面重量超过了1.1MB,图像的重量增加了88%。我也意识到我正在提供比他们需要的更大的图像(就分辨率而言)。显然,还有很大的改进空间。

我开始阅读Addy Osmani 的优秀Essential Image Optimization电子书,并开始在我的网站上实施他的建议。然后我对响应式图像进行了一些研究,并将其应用于此。

这使页面重量降至445kb。页面重量减少约62%!

本文是关于描述我将主页的页面权重提升到更易管理的水平的步骤。

什么是图像压缩?

压缩图像就是在保持可接受的视觉质量水平的同时减小文件大小。要压缩我网站上的图像,imagemin是我的首选工具。

要使用imagemin,请确保已安装Node.js然后打开终端窗口,cd进入项目的文件夹并运行以下命令:

npm install imagemin

然后创建一个名为的新文件imagemin.js并粘贴到以下内容中:

const imagemin = require('imagemin'); 
const PNGImages ='assets/images/*.png';
const JPEGImages ='assets/images/*.jpg';
const output ='build/images';

随意更改PNGImagesJPEGImagesoutput匹配您的项目的结构。

要执行任何压缩,您需要根据要压缩的图像类型提取一些插件。

使用MozJPEG压缩JPEG

为了压缩JPEG图像,我使用了Mozilla 的MozJPEG工具,它可以通过imagemin- mozjpeg作为Imagemin插件使用。您可以通过运行以下命令来安装它:

npm install imagemin-mozjpeg

然后将以下内容添加到您的imagemin.js文件中:

const imageminMozjpeg = require('imagemin-mozjpeg');
const 
 optimiseJPEGImages =()=> imagemin([JPEGImages],输出,{
   plugins:[
     imageminMozjpeg({
       quality:70,
     }),
   ]
 });

 optimiseJPEGImages().catch(error => console.log(error));

您可以通过node imagemin.js在终端中运行来运行脚本。这将处理所有JPEG图像,并将优化版本放在build/images文件夹中。

我发现,设置quality70产生大部分足够好的图像,但您的里程可能会有所不同。根据您的需要尝试使用该值。

MozJPEG默认情况下会生成渐进式JPEG,这会导致图像从低分辨率逐渐加载到更高分辨率,直到图像完全加载为止。由于它们的编码方式,它们也往往略小于基线JPEG。

您可以使用Sindre Sorhus的这个漂亮的命令行工具来检查JPEG图像是否是渐进的。

优点缺点使用渐进式JPEG已经由阿迪·奥斯马尼得到了很好的证明。对我来说,我觉得专业人士超过了缺点,所以我坚持默认设置。

如果你喜欢使用基线JPEG文件,而不是,您可以设置progressivefalse在选择对象。此外,请务必重新访问imagemin-mozjpeg页面以查看您可以修改的其他可用设置。

使用pngquant优化PNG图像

pngquant是我优化PNG图像的首选工具。你可以通过imagemin-pngquant使用它:

npm install imagemin-pngquant

然后将以下内容添加到您的imagemin.js文件中:

const imageminPngquant = require('imagemin-pngquant');
const 
 optimisePNGImages =()=> imagemin([PNGImages],output,{
   plugins:[
     imageminPngquant({quality:'65 -80'})
   ],
 });
optimiseJPEGImages() 
 .then(()=> optimisePNGImages())
 .catch(error=>console.log(error));

我发现一个quality水平65-80提供文件大小和图像质量之间的良好平衡。

通过这些设置,我能够从913 KB到187 KB获取我的网站的屏幕截图,没有任何可辨别的视觉质量损失。百分比减少了79%!

这是两个文件。看看并自己判断:

将WebP图像提供给支持它们的浏览器

WebP是Google推出的一种相对较新的格式,旨在通过编码无损有损格式的图像来提供较小的文件大小,使其成为JPEG和PNG的绝佳替代品。

WebP图像的视觉质量通常与JPEG和PNG相当,但通常文件大小要小得多。例如,当我将屏幕截图从上面转换为WebP时,我得到了一个88 KB的文件,其质量与913 KB的原始图像相当。减少90%!

看看这三张图片。你能分辨出来吗?

就个人而言,我认为视觉质量具有可比性,您所获得的节省很难被忽视。

现在我们已经确定了尽可能使用WebP格式的价值,重要的是要注意 – 此时 – 它不能完全取代JPEG和PNG,因为浏览器中的WebP支持并不普遍。

在撰写本文时,Firefox,Safari和Edge是没有WebP支持的着名浏览器。

然而,根据caniuse.com,全球超过70%的用户使用支持WebP的浏览器。这意味着,通过提供WebP图像,您可以为大约70%的客户提高网页速度。

我们来看看在Web上提供WebP图像的确切步骤。

将JPEG和PNG转换为WebP

使用imagemin-webp插件将JPEG和PNG图像转换为WebP非常简单。

通过在终端中运行以下命令来安装它:

npm install imagemin-webp

然后将以下内容添加到您的imagemin.js文件中:

const imageminWebp = require('imagemin-webp');
const convertPNGToWebp =()=> 
 imagemin([PNGImages],output,{
   use:[
     imageminWebp({
       quality:85,
     }),
   ]
 });
const convertJPGToWebp =()=> 
 imagemin([JPGImages],output,{
   use:[
     imageminWebp({
       quality:75,
     }),
   ]
 });
optimiseJPEGImages() 
 .then(()=> optimisePNGImages())
 .then(()=> convertPNGToWebp())
 .then(()=> convertJPGToWebp())
 .catch(error =>console.log(error));

我发现设置quality85生成WebP图像,其质量与PNG等效,但大幅缩小。对于JPEG文件,我发现,设置quality75给我的视觉质量和文件大小之间的平衡得体。

说实话,我还在尝试这些价值观,所以不要把它们作为推荐。并确保重新检查imagemin-webp页面以查看可供您使用的其他选项。

以HTML格式提供WebP图像

获得WebP图像后,您可以使用以下标记将它们提供给可以使用它们的浏览器,同时为没有WebP支持的浏览器提供等效(优化)JPEG或PNG后备。

<picture> 
   <source srcset =“sample_image.webp”type =“image/webp”>
   <source srcset =“sample_image.jpg”type =“image/jpg”>
   <img src =“sample_image.jpg”alt =“” >
</ picture>

使用此标记,了解image/webp媒体类型的浏览器将下载WebP变体并显示它,而其他浏览器将下载JPEG变体。

任何不理解的浏览器都<picture>将跳过所有source并加载底部标签src属性中定义的所有内容img。因此,我们通过为所有类浏览器提供支持来逐步增强页面。

请注意,在所有情况下,img标记都是实际呈现给页面的内容,因此它确实是语法的必需部分。如果遗漏img标记,则不会渲染任何图像。

<picture>标记和所有的source内部规定就在那里,这样浏览器就可以选择要使用的图像的变形。选择源图像后,其URL将被输入img标签,这就是显示的内容。

这意味着您不需要设置样式<picture>source标记,因为浏览器不会呈现这些样式。因此,您可以img像以前一样继续使用标签样式。

总结

正如您所看到的,优化图像以便在Web上使用的过程并不复杂,可以通过减少页面加载时间为您的客户带来更好的用户体验。所以今天花几分钟时间在您的网站上进行一些图像优化。如果您有其他建议,请务必在评论或Twitter上提及。

初识 图片压缩 MozJPEG 之 CentOS 7 编译安装

官方教程

https://github.com/mozilla/mozjpeg/blob/master/BUILDING.txt

源码地址

https://github.com/mozilla/mozjpeg/releases

需 nasm 环境

yum -y install build-essential nasm

以 3.3.1 为例

cd ~
wget -O "mozjpeg-3.3.1.tar.gz" https://codeload.github.com/mozilla/mozjpeg/tar.gz/v3.3.1
tar -zxvf mozjpeg-v3.3.1.tar.gz 
cd mozjpeg-3.3.1
autoreconf -fiv
./configure
make
make install

安装完成 目录

/opt/mozjpeg/bin
-rwxr-xr-x 1 root root 56752 Nov  2 23:26 cjpeg
-rwxr-xr-x 1 root root 45792 Nov  2 23:26 djpeg
-rwxr-xr-x 1 root root 53424 Nov  2 23:26 jpegtran
-rwxr-xr-x 1 root root 13536 Nov  2 23:26 rdjpgcom
-rwxr-xr-x 1 root root 64456 Nov  2 23:26 tjbench
-rwxr-xr-x 1 root root 13552 Nov  2 23:26 wrjpgcom

使用示例

/opt/mozjpeg/bin/cjpeg -quality 80 a.jpg > a1.jpg

图片由 4.9MB 压缩至 1.4MB

帮助文档

[root@instance-jewlel2q bin]# ./cjpeg -h
./cjpeg: unknown option 'h'
usage: ./cjpeg [switches] [inputfile]
Switches (names may be abbreviated):
  -quality N[,...]   Compression quality (0..100; 5-95 is most useful range,
                     default is 75)
  -grayscale     Create monochrome JPEG file
  -rgb           Create RGB JPEG file
  -optimize      Optimize Huffman table (smaller file, but slow compression, enabled by default)
  -progressive   Create progressive JPEG file (enabled by default)
  -baseline      Create baseline JPEG file (disable progressive coding)
  -targa         Input file is Targa format (usually not needed)
  -revert        Revert to standard defaults (instead of mozjpeg defaults)
  -fastcrush     Disable progressive scan optimization
  -dc-scan-opt   DC scan optimization mode
                 - 0 One scan for all components
                 - 1 One scan per component (default)
                 - 2 Optimize between one scan for all components and one scan for 1st component
                     plus one scan for remaining components
  -notrellis     Disable trellis optimization
  -trellis-dc    Enable trellis optimization of DC coefficients (default)
  -notrellis-dc  Disable trellis optimization of DC coefficients
  -tune-psnr     Tune trellis optimization for PSNR
  -tune-hvs-psnr Tune trellis optimization for PSNR-HVS (default)
  -tune-ssim     Tune trellis optimization for SSIM
  -tune-ms-ssim  Tune trellis optimization for MS-SSIM
Switches for advanced users:
  -noovershoot   Disable black-on-white deringing via overshoot
  -arithmetic    Use arithmetic coding
  -dct int       Use integer DCT method (default)
  -dct fast      Use fast integer DCT (less accurate)
  -dct float     Use floating-point DCT method
  -quant-baseline Use 8-bit quantization table entries for baseline JPEG compatibility
  -quant-table N Use predefined quantization table N:
                 - 0 JPEG Annex K
                 - 1 Flat
                 - 2 Custom, tuned for MS-SSIM
                 - 3 ImageMagick table by N. Robidoux
                 - 4 Custom, tuned for PSNR-HVS
                 - 5 Table from paper by Klein, Silverstein and Carney
  -restart N     Set restart interval in rows, or in blocks with B
  -smooth N      Smooth dithered input (N=1..100 is strength)
  -maxmemory N   Maximum memory to use (in kbytes)
  -outfile name  Specify name for output file
  -memdst        Compress to memory instead of file (useful for benchmarking)
  -verbose  or  -debug   Emit debug output
  -version       Print version information and exit
Switches for wizards:
  -qtables FILE  Use quantization tables given in FILE
  -qslots N[,...]    Set component quantization tables
  -sample HxV[,...]  Set component sampling factors
  -scans FILE    Create multi-scan JPEG per script FILE
[root@instance-jewlel2q bin]# ./djpeg -h
usage: ./djpeg [switches] [inputfile]
Switches (names may be abbreviated):
  -colors N      Reduce image to no more than N colors
  -fast          Fast, low-quality processing
  -grayscale     Force grayscale output
  -rgb           Force RGB output
  -rgb565        Force RGB565 output
  -scale M/N     Scale output image by fraction M/N, eg, 1/8
  -bmp           Select BMP output format (Windows style)
  -gif           Select GIF output format
  -os2           Select BMP output format (OS/2 style)
  -pnm           Select PBMPLUS (PPM/PGM) output format (default)
  -targa         Select Targa output format
Switches for advanced users:
  -dct int       Use integer DCT method (default)
  -dct fast      Use fast integer DCT (less accurate)
  -dct float     Use floating-point DCT method
  -dither fs     Use F-S dithering (default)
  -dither none   Don't use dithering in quantization
  -dither ordered  Use ordered dither (medium speed, quality)
  -map FILE      Map to colors used in named image file
  -nosmooth      Don't use high-quality upsampling
  -onepass       Use 1-pass quantization (fast, low quality)
  -maxmemory N   Maximum memory to use (in kbytes)
  -outfile name  Specify name for output file
  -memsrc        Load input file into memory before decompressing
  -skip Y0,Y1    Decompress all rows except those between Y0 and Y1 (inclusive)
  -crop WxH+X+Y  Decompress only a rectangular subregion of the image
  -verbose  or  -debug   Emit debug output
  -version       Print version information and exit
[root@instance-jewlel2q bin]# ./jpegtran -h
usage: ./jpegtran [switches] [inputfile]
Switches (names may be abbreviated):
  -copy none     Copy no extra markers from source file
  -copy comments Copy only comment markers (default)
  -copy all      Copy all extra markers
  -optimize      Optimize Huffman table (smaller file, but slow compression, enabled by default)
  -progressive   Create progressive JPEG file (enabled by default)
  -revert        Revert to standard defaults (instead of mozjpeg defaults)
  -fastcrush     Disable progressive scan optimization
Switches for modifying the image:
  -crop WxH+X+Y  Crop to a rectangular subarea
  -grayscale     Reduce to grayscale (omit color data)
  -flip [horizontal|vertical]  Mirror image (left-right or top-bottom)
  -perfect       Fail if there is non-transformable edge blocks
  -rotate [90|180|270]         Rotate image (degrees clockwise)
  -transpose     Transpose image
  -transverse    Transverse transpose image
  -trim          Drop non-transformable edge blocks
Switches for advanced users:
  -arithmetic    Use arithmetic coding
  -restart N     Set restart interval in rows, or in blocks with B
  -maxmemory N   Maximum memory to use (in kbytes)
  -outfile name  Specify name for output file
  -verbose  or  -debug   Emit debug output
  -version       Print version information and exit
Switches for wizards:
  -scans FILE    Create multi-scan JPEG per script FILE
[root@instance-jewlel2q bin]# ./rdjpgcom -h
rdjpgcom displays any textual comments in a JPEG file.
Usage: ./rdjpgcom [switches] [inputfile]
Switches (names may be abbreviated):
  -raw        Display non-printable characters in comments (unsafe)
  -verbose    Also display dimensions of JPEG image
[root@instance-jewlel2q bin]# ./tjbench -h

USAGE: ./tjbench
       <Inputfile (BMP|PPM)> <Quality> [options]

       ./tjbench
       <Inputfile (JPG)> [options]

Options:

-alloc = Dynamically allocate JPEG image buffers
-bmp = Generate output images in Windows Bitmap format (default = PPM)
-bottomup = Test bottom-up compression/decompression
-tile = Test performance of the codec when the image is encoded as separate
     tiles of varying sizes.
-rgb, -bgr, -rgbx, -bgrx, -xbgr, -xrgb =
     Test the specified color conversion path in the codec (default = BGR)
-cmyk = Indirectly test YCCK JPEG compression/decompression (the source
     and destination bitmaps are still RGB.  The conversion is done
     internally prior to compression or after decompression.)
-fastupsample = Use the fastest chrominance upsampling algorithm available in
     the underlying codec
-fastdct = Use the fastest DCT/IDCT algorithms available in the underlying
     codec
-accuratedct = Use the most accurate DCT/IDCT algorithms available in the
     underlying codec
-subsamp <s> = When testing JPEG compression, this option specifies the level
     of chrominance subsampling to use (<s> = 444, 422, 440, 420, 411, or
     GRAY).  The default is to test Grayscale, 4:2:0, 4:2:2, and 4:4:4 in
     sequence.
-quiet = Output results in tabular rather than verbose format
-yuv = Test YUV encoding/decoding functions
-yuvpad <p> = If testing YUV encoding/decoding, this specifies the number of
     bytes to which each row of each plane in the intermediate YUV image is
     padded (default = 1)
-scale M/N = Scale down the width/height of the decompressed JPEG image by a
     factor of M/N (M/N = 2/1, 15/8, 7/4, 13/8, 3/2, 11/8, 5/4, 9/8, 1/1, 
     7/8, 3/4, 5/8, 1/2, 3/8, 1/4, or 1/8)
-hflip, -vflip, -transpose, -transverse, -rot90, -rot180, -rot270 =
     Perform the corresponding lossless transform prior to
     decompression (these options are mutually exclusive)
-grayscale = Perform lossless grayscale conversion prior to decompression
     test (can be combined with the other transforms above)
-benchtime <t> = Run each benchmark for at least <t> seconds (default = 5.0)
-warmup <t> = Run each benchmark for <t> seconds (default = 1.0) prior to
     starting the timer, in order to prime the caches and thus improve the
     consistency of the results.
-componly = Stop after running compression tests.  Do not test decompression.
-nowrite = Do not write reference or output images (improves consistency of
     performance measurements.)

NOTE:  If the quality is specified as a range (e.g. 90-100), a separate
test will be performed for all quality values in the range.
[root@instance-jewlel2q bin]# ./wrjpgcom -h
wrjpgcom inserts a textual comment in a JPEG file.
You can add to or replace any existing comment(s).
Usage: ./wrjpgcom [switches] [inputfile]
Switches (names may be abbreviated):
  -replace         Delete any existing comments
  -comment "text"  Insert comment with given text
  -cfile name      Read comment from named file
Notice that you must put quotes around the comment text
when you use -comment.
If you do not give either -comment or -cfile on the command line,
then the comment text is read from standard input.
It can be multiple lines, up to 65000 characters total.
You must specify an input JPEG file name when supplying
comment text from standard input.