spring注解@Scheduled

注解@Scheduled 可以作为一个触发源添加到一个方法中,例如,以下的方法将以一个固定延迟时间5秒钟调用一次执行,这个周期是以上一个调用任务的完成时间为基准,在上一个任务完成之后,5s后再次执行:

@Scheduled(fixedDelay = 5000)
public void doSomething() { 
// something that should execute periodically
}

如果需要以固定速率执行,只要将注解中指定的属性名称改成fixedRate即可,以下方法将以一个固定速率5s来调用一次执行,这个周期是以上一个任务开始时间为基准,从上一任务开始执行后5s再次调用:

@Scheduled(fixedRate = 5000)
public void doSomething() { 
// something that should execute periodically
}

Cron表达式

网站自动生成:http://cron.qqe2.com/

字段 通配符
0-59 , - * /
0-59 , - * /
小时 0-23 , - * /
日期 1-31 , - * ? / L W C
月份 1-12 或者 JAN-DEC , - * /
星期 1-7 或者 SUN-SAT , - * ? / L C #
年(可选) 留空, 1970-2099 , - * /

例子:

0 0 10,14,16 * * ? 每天上午10点,下午2点,4点
0 0/30 9-17 * * ? 朝九晚五工作时间内每半小时
0 0 12 ? * WED 表示每个星期三中午12点
“0 0 12 * * ?” 每天中午12点触发
“0 15 10 ? * *” 每天上午10:15触发
“0 15 10 * * ?” 每天上午10:15触发
“0 15 10 * * ? *” 每天上午10:15触发
“0 15 10 * * ? 2005″ 2005年的每天上午10:15触发
“0 * 14 * * ?” 在每天下午2点到下午2:59期间的每1分钟触发
“0 0/5 14 * * ?” 在每天下午2点到下午2:55期间的每5分钟触发
“0 0/5 14,18 * * ?” 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
“0 0-5 14 * * ?” 在每天下午2点到下午2:05期间的每1分钟触发
“0 10,44 14 ? 3 WED” 每年三月的星期三的下午2:10和2:44触发
“0 15 10 ? * MON-FRI” 周一至周五的上午10:15触发
“0 15 10 15 * ?” 每月15日上午10:15触发
“0 15 10 L * ?” 每月最后一日的上午10:15触发
“0 15 10 ? * 6L” 每月的最后一个星期五上午10:15触发
“0 15 10 ? * 6L 2002-2005″ 2002年至2005年的每月的最后一个星期五上午10:15触发
“0 15 10 ? * 6#3″ 每月的第三个星期五上午10:15触发

有些子表达式能包含一些范围或列表

例如:子表达式(天(星期))可以为 “MON-FRI”,“MON,WED,FRI”,“MON-WED,SAT”

“*”字符代表所有可能的值

因此,“*”在子表达式(月)里表示每个月的含义,“*”在子表达式(天(星期))表示星期的每一天

“/”字符用来指定数值的增量

例如:在子表达式(分钟)里的“0/15”表示从第0分钟开始,每15分钟

在子表达式(分钟)里的“3/20”表示从第3分钟开始,每20分钟(它和“3,23,43”)的含义一样
“?”字符仅被用于天(月)和天(星期)两个子表达式,表示不指定值

当2个子表达式其中之一被指定了值以后,为了避免冲突,需要将另一个子表达式的值设为“?”

“L” 字符仅被用于天(月)和天(星期)两个子表达式,它是单词“last”的缩写

但是它在两个子表达式里的含义是不同的。

在天(月)子表达式中,“L”表示一个月的最后一天

在天(星期)自表达式中,“L”表示一个星期的最后一天,也就是SAT

如果在“L”前有具体的内容,它就具有其他的含义了

例如:“6L”表示这个月的倒数第6天,“FRIL”表示这个月的最一个星期五

注意:在使用“L”参数时,不要指定列表或范围,因为这会导致问题

JDK中jstack、jmap、jstat工具使用说明

  • jstack 查看线程
  • jmap 查看内存
  • jstat 性能分析

jmap摘要

jmap [ option ] pid
jmap [ option ] executable core
jmap [ option ] [server-id@]remote-hostname-or-IP

jmap参数

option
选项是互斥的。如果使用了选项,则应紧随命令名称之后。

pid
要为其打印内存映射的进程ID。该进程必须是Java进程。要获取机器上运行的Java进程的列表, 可以使用jps。

executable
Java executable from which the core dump was produced.(生成核心转储的Java可执行文件。)

core
core file for which the memory map is to be printed.(要为其打印内存映射的核心文件。)

remote-hostname-or-IP
远程调试服务器的主机名或IP地址。

server-id
如果多个调试服务器在同一远程主机上运行,​​则为可选的唯一ID。

描述
jmap打印给定进程或核心文件或远程调试服务器的共享对象内存映射或堆内存详细信息。如果给定进程在64位VM上运行,则可能需要指定-J-d64选项,例如:
jmap -J-d64 -heap pid

注意:
此实用程序不受支持,在JDK的将来版本中可能可用,也可能不可用。在不存在dbgeng.dll的 Windows系统中,需要安装“ Windows调试工具”才能使这些工具正常工作。另外,PATH环境变量应包含目标进程使用的jvm.dll的位置或从中生成故障转储文件的位置。

For example, set PATH=<jdk>\jre\bin\client;%PATH%

jmap参数选项

    <no option>
    如果不使用任何选项,则jmap将打印共享对象映射。对于目标VM中加载的每个共享库,将打印起始地址,映射的大小以及共享库文件的完整路径。这类似于Solaris pmap实用程序。

    -dump:[live,]format=b,file=<filename>
    Dumps the Java heap in hprof binary format to filename. The live suboption is optional. If specified, only the live objects in the heap are dumped. To browse the heap dump, you can use jhat (Java Heap Analysis Tool) to read the generated file.
    (将hprof二进制格式的Java堆转储到文件名。该live参数是可选的,如果指定,则仅转储堆中的活动对象。要浏览堆转储,可以使用jhat (Java堆分析工具)读取生成的文件。)

    -finalizerinfo
    Prints information on objects awaiting finalization.(在等待完成的对象上打印信息。)

    -heap
    Prints a heap summary. GC algorithm used, heap configuration and generation wise heap usage are printed.
    (打印堆摘要。打印使用的GC算法,堆配置和生成明智的堆用法。)

    -histo[:live]
    Prints a histogram of the heap. For each Java class, number of objects, memory size in bytes, and fully qualified class names are printed. VM internal class names are printed with '*' prefix. If the live suboption is specified, only live objects are counted.
    (打印堆的直方图。对于每个Java类,将打印对象数量,以字节为单位的内存大小以及完全限定的类名称。VM内部类名称以“ *”前缀打印。如果指定了live子选项,则仅计算活动对象。)

    -permstat
    Prints class loader wise statistics of permanent generation of Java heap. For each class loader, its name, liveness, address, parent class loader, and the number and size of classes it has loaded are printed. In addition, the number and size of interned Strings are printed.
    (打印永久生成的Java堆的类加载器明智的统计信息。对于每个类加载器,将打印其名称,活动性,地址,父类加载器以及已加载的类的数量和大小。此外,还会打印实习字符串的数量和大小。)

    -F
    Force. Use with jmap -dump or jmap -histo option if the pid does not respond. The live suboption is not supported in this mode.

    -h
    Prints a help message.

    -help
    Prints a help message.

    -J<flag>
    Passes <flag> to the Java virtual machine on which jmap is run.

jstack摘要

jstack [ option ] pid
jstack [ option ] executable core
jstack [ option ] [server-id@]remote-hostname-or-IP

jstack参数

option
选项是互斥的。如果使用了选项,则应紧随命令名称之后。

pid
要为其打印内存映射的进程ID。该进程必须是Java进程。要获取机器上运行的Java进程的列表, 可以使用jps。

executable
Java executable from which the core dump was produced.(生成核心转储的Java可执行文件。)

core
core file for which the memory map is to be printed.(要为其打印内存映射的核心文件。)

remote-hostname-or-IP
远程调试服务器的主机名或IP地址。

server-id
如果多个调试服务器在同一远程主机上运行,​​则为可选的唯一ID。

描述
jstack为给定的Java进程或核心文件或远程调试服务器打印Java线程的Java堆栈跟踪。对于每个Java框架,将打印完整的类名,方法名,“ bci”(字节码索引)和行号(如果有)。使用-m选项,jstack可以同时打印所有线程的Java和本机框架以及“ pc”(程序计数器)。对于每个本机帧,将打印与“ pc”最接近的本机符号(如果有)。C ++杂乱无章的名称不会被删除。要对C ++名称进行解密,可以将此命令的输出传递给c ++ filt。如果给定进程在64位VM上运行,则可能需要指定-J-d64选项,例如:
jstack -J-d64 -m pid

注意:
此实用程序不受支持,在JDK的将来版本中可能可用,也可能不可用。在不存在dbgent.dll的 Windows系统中,需要安装“ Windows调试工具”才能使这些工具正常工作。另外,PATH环境变量应包含目标进程使用的jvm.dll的位置或从中生成故障转储文件的位置。
For example, set PATH=<jdk>\jre\bin\client;%PATH%

参数选项

        -F
        Force a stack dump when 'jstack [-l] pid' does not respond.
        -l
        Long listing. Prints additional information about locks such as list of owned java.util.concurrent ownable synchronizers.
        -m
        prints mixed mode (both Java and native C/C++ frames) stack trace.
        -h
        prints a help message.

        -help
        prints a help message

 

Jstat概要

Jstat是JDK自带的一个轻量级小工具。全称“Java Virtual Machine statistics monitoring tool”,它位于java的bin目录下,主要利用JVM内建的指令对Java应用程序的资源和性能进行实时的命令行的监控,包括了对Heap size和垃圾回收状况的监控。可见,Jstat是轻量级的、专门针对JVM的工具,非常适用。

  •  jstat -class pid:显示加载class的数量,及所占空间等信息。
  • jstat -compiler pid:显示VM实时编译的数量等信息。
  • jstat -gc pid:可以显示gc的信息,查看gc的次数,及时间。其中最后五项,分别是young gc的次数,young gc的时间,full gc的次数,full gc的时间,gc的总时间。
  • jstat -gccapacity:可以显示,VM内存中三代(young,old,perm)对象的使用和占用大小,如:PGCMN显示的是最小perm的内存使用量,PGCMX显示的是perm的内存最大使用量,PGC是当前新生成的perm内存占用量,PC是但前perm内存占用量。其他的可以根据这个类推, OC是old内纯的占用量。
  • jstat -gcnew pid:new对象的信息。
  • jstat -gcnewcapacity pid:new对象的信息及其占用量。
  • jstat -gcold pid:old对象的信息。
  • jstat -gcoldcapacity pid:old对象的信息及其占用量。
  • jstat -gcpermcapacity pid: perm对象的信息及其占用量。
  • jstat -util pid:统计gc信息统计。
  • jstat -printcompilation pid:当前VM执行的信息。

除了以上一个参数外,还可以同时加上 两个数字,如:jstat -printcompilation 3024 250 6是每250毫秒打印一次,一共打印6次,还可以加上-h3每三行显示一下标题。

jstat命令详解

jstat -gc pid
可以显示gc的信息,查看gc的次数,及时间。
其中最后五项,分别是young gc的次数,young gc的时间,full gc的次数,full gc的时间,gc的总时间。
jstat -gccapacity pid
可以显示,VM内存中三代(young,old,perm)对象的使用和占用大小,
如:PGCMN显示的是最小perm的内存使用量,PGCMX显示的是perm的内存最大使用量,
PGC是当前新生成的perm内存占用量,PC是但前perm内存占用量。
其他的可以根据这个类推, OC是old内纯的占用量。
jstat -gcutil pid
统计gc信息统计。
jstat -gcnew pid
年轻代对象的信息。
jstat -gcnewcapacity pid
年轻代对象的信息及其占用量。
jstat -gcold pid
old代对象的信息。
stat -gcoldcapacity pid
old代对象的信息及其占用量。
jstat -gcpermcapacity pid
perm对象的信息及其占用量。
jstat -class pid
显示加载class的数量,及所占空间等信息。
jstat -compiler pid
显示VM实时编译的数量等信息。
stat -printcompilation pid
当前VM执行的信息。

 一些术语的中文解释:

S0C:年轻代中第一个survivor(幸存区)的容量(字节)
S1C:年轻代中第二个survivor(幸存区)的容量(字节)
S0U:年轻代中第一个survivor(幸存区)目前已使用空间(字节)
S1U:年轻代中第二个survivor(幸存区)目前已使用空间(字节)
EC:年轻代中Eden(伊甸园)的容量(字节)
EU:年轻代中Eden(伊甸园)目前已使用空间(字节)
OC:Old代的容量(字节)
OU:Old代目前已使用空间(字节)
PC:Perm(持久代)的容量(字节)
PU:Perm(持久代)目前已使用空间(字节)
YGC:从应用程序启动到采样时年轻代中gc次数
YGCT:从应用程序启动到采样时年轻代中gc所用时间(s)
FGC:从应用程序启动到采样时old代(全gc)gc次数
FGCT:从应用程序启动到采样时old代(全gc)gc所用时间(s)
GCT:从应用程序启动到采样时gc用的总时间(s)
NGCMN:年轻代(young)中初始化(最小)的大小(字节)
NGCMX:年轻代(young)的最大容量(字节)
NGC:年轻代(young)中当前的容量(字节)
OGCMN:old代中初始化(最小)的大小(字节)
OGCMX:old代的最大容量(字节)
OGC:old代当前新生成的容量(字节)
PGCMN:perm代中初始化(最小)的大小(字节)
PGCMX:perm代的最大容量(字节)
PGC:perm代当前新生成的容量(字节)
S0:年轻代中第一个survivor(幸存区)已使用的占当前容量百分比
S1:年轻代中第二个survivor(幸存区)已使用的占当前容量百分比
E:年轻代中Eden(伊甸园)已使用的占当前容量百分比
O:old代已使用的占当前容量百分比
P:perm代已使用的占当前容量百分比
S0CMX:年轻代中第一个survivor(幸存区)的最大容量(字节)
S1CMX:年轻代中第二个survivor(幸存区)的最大容量(字节)
ECMX:年轻代中Eden(伊甸园)的最大容量(字节)
DSS:当前需要survivor(幸存区)的容量(字节)

 

 

 

CentOS 7x安装Mysql8.0.x

其实官网有教程的,我这里记录下来,是因为要写一个自动化安装脚本,虽然不经常用到,但是还是写出来比较好。

Mysql8.0仅支持CentOS 7x系统下安装,反正6.5的测试过一次,但是安装成功,启动失败,原因是缺少依赖。

Mysql8.0相信只会安装到64位的机器上。

  • 首先,下载mysql8.0的压缩包:

# wget https://dev.mysql.com/get/Downloads/MySQL-8.0/mysql-8.0.18-linux-glibc2.12-x86_64.tar.xz
# wget https://dev.mysql.com/get/Downloads/MySQL-8.0/mysql-8.0.18-el7-x86_64.tar.gz
# wget http://mysql.mirror.kangaroot.net/Downloads/MySQL-8.0/mysql-8.0.18-el7-x86_64.tar.gz
wget http://ftp.ntu.edu.tw/MySQL/Downloads/MySQL-8.0/mysql-8.0.18-el7-x86_64.tar.gz

我测试了最后一个,下载速度最快,所以贴上来好了。

  • 解压缩

tar -xzvf mysql-8.0.18-el7-x86_64.tar.gz
mv mysql-8.0.18-el7-x86_64/* /alidata/server/mysql
mkdir -p /alidata/server/mysql/data
ln -s /alidata/server/mysql-8.0.18 /usr/local/mysql
chmod 777 /alidata/server/mysql
chmod 777 /alidata/server/mysql/data

  • 权限配置

groupadd mysql
useradd -g mysql -s /sbin/nologin mysql
chown -R mysql:mysql /alidata/server/mysql/
chown -R mysql:mysql /alidata/server/mysql/data/
chown -R mysql:mysql /alidata/log/mysql
chmod -R 777 /alidata/server/mysql/support-files
chmod -R 777 /alidata/server/mysql/bin
\cp -f /alidata/server/mysql/support-files/mysql.server /etc/init.d/mysqld
sed -i ‘s#^basedir=$#basedir=/alidata/server/mysql#’ /etc/init.d/mysqld
sed -i ‘s#^datadir=$#datadir=/alidata/server/mysql/data#’ /etc/init.d/mysqld

  • 输出my.cnf文件

cat > /etc/my.cnf <<END
[client]
port=3306
default-character-set=utf8
[mysqld]
port = 3306
socket = /tmp/mysql.sock
default_authentication_plugin=mysql_native_password
skip-external-locking
log-error=/alidata/log/mysql/error.log
character-set-server=utf8
default-storage-engine=INNODB
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

log-bin=mysql-bin
binlog_format=mixed
server-id = 1

innodb_buffer_pool_size=512M
innodb_flush_log_at_trx_commit=1
innodb_lock_wait_timeout=120
innodb_log_buffer_size=4M
innodb_log_file_size=256M
interactive_timeout=120
join_buffer_size=2M
key_buffer_size=32M
max_allowed_packet=16M
max_connections=100
max_heap_table_size=64M
myisam_max_sort_file_size=64G
myisam_sort_buffer_size=32M
read_buffer_size=512kb
read_rnd_buffer_size=4M
server_id=1
skip-external-locking=on
sort_buffer_size=256kb
table_open_cache=256
thread_cache_size=16
tmp_table_size=64M
wait_timeout=120

[mysql]
default-character-set=utf8
END

  • 最后,安装并启动

/alidata/server/mysql/bin/mysqld –initialize –user=mysql
chmod 755 /etc/init.d/mysqld
/etc/init.d/mysqld start

*需要注意:

mysql8.0安装成功后,会把初始密码写到log-error对应的文件中,我这里设置的路径是/alidata/log/mysql/error.log,打开这个文件,找到密码,并使用:mysql -uroot -p

登陆终端,把密码修改了,不然的话登陆上去,也操作不了其他。

修改密码的代码:

#alter user ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘bsiidno6gH0′;
#flush privileges

最后,贴出整个shell代码:

#!/bin/bash

yum install -y libaio

ifubuntu=$(cat /proc/version | grep ubuntu)
if14=$(cat /etc/issue | grep 14)

if [ `uname -m` == "x86_64" ];then
machine=x86_64
else
machine=i686
fi
if [ $machine == "x86_64" ];then
  rm -rf mysql-8.0.18-el7-x86_64
  if [ ! -f mysql-8.0.18-el7-x86_64.tar.gz ];then
#   wget http://zy-res.oss-cn-hangzhou.aliyuncs.com/mysql/mysql-5.6.21-linux-glibc2.5-x86_64.tar.gz
#   wget https://dev.mysql.com/get/Downloads/MySQL-8.0/mysql-8.0.18-linux-glibc2.12-x86_64.tar.xz
#   wget https://dev.mysql.com/get/Downloads/MySQL-8.0/mysql-8.0.18-el7-x86_64.tar.gz
#   wget http://mysql.mirror.kangaroot.net/Downloads/MySQL-8.0/mysql-8.0.18-el7-x86_64.tar.gz
    wget http://ftp.ntu.edu.tw/MySQL/Downloads/MySQL-8.0/mysql-8.0.18-el7-x86_64.tar.gz
  fi
  tar -xzvf mysql-8.0.18-el7-x86_64.tar.gz
  mv mysql-8.0.18-el7-x86_64/* /alidata/server/mysql
  mkdir -p /alidata/server/mysql/data
  ln -s /alidata/server/mysql-8.0.18 /usr/local/mysql
  chmod 777 /alidata/server/mysql   
  chmod 777 /alidata/server/mysql/data

else
  echo 'unsupport machine i686'
fi

if [ "$ifubuntu" != "" ] && [ "$if14" != "" ];then
   mv /etc/mysql/my.cnf /etc/mysql/my.cnf.bak
fi

groupadd mysql
useradd -g mysql -s /sbin/nologin mysql
chown -R mysql:mysql /alidata/server/mysql/
chown -R mysql:mysql /alidata/server/mysql/data/
chown -R mysql:mysql /alidata/log/mysql
chmod  -R 777 /alidata/server/mysql/support-files
chmod  -R 777 /alidata/server/mysql/bin
\cp -f /alidata/server/mysql/support-files/mysql.server /etc/init.d/mysqld
sed -i 's#^basedir=$#basedir=/alidata/server/mysql#' /etc/init.d/mysqld
sed -i 's#^datadir=$#datadir=/alidata/server/mysql/data#' /etc/init.d/mysqld
cat > /etc/my.cnf <<END
[client]
port=3306
default-character-set=utf8
[mysqld]
port            = 3306
socket          = /tmp/mysql.sock
default_authentication_plugin=mysql_native_password
skip-external-locking
log-error=/alidata/log/mysql/error.log
character-set-server=utf8
default-storage-engine=INNODB
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

log-bin=mysql-bin
binlog_format=mixed
server-id       = 1

innodb_buffer_pool_size=512M
innodb_flush_log_at_trx_commit=1
innodb_lock_wait_timeout=120
innodb_log_buffer_size=4M
innodb_log_file_size=256M
interactive_timeout=120
join_buffer_size=2M
key_buffer_size=32M
max_allowed_packet=16M
max_connections=100
max_heap_table_size=64M
myisam_max_sort_file_size=64G
myisam_sort_buffer_size=32M
read_buffer_size=512kb
read_rnd_buffer_size=4M
server_id=1
skip-external-locking=on
sort_buffer_size=256kb
table_open_cache=256
thread_cache_size=16
tmp_table_size=64M
wait_timeout=120

[mysql]
default-character-set=utf8


END

/alidata/server/mysql/bin/mysqld --initialize --user=mysql
chmod 755 /etc/init.d/mysqld
/etc/init.d/mysqld start

#mysql password see @/alidata/log/mysql/error.log
#and must by alter root password.
#
#alter user 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'bsiidno6gH0';
#flush privileges
#use mysql mysql
#update user set user.Host='%'where user.User='root';
#export PATH=$PATH:/alidata/server/mysql/bin
#
#/alidata/server/php/bin/php -f ./res/init_mysql.php

官方文档:

https://dev.mysql.com/doc/refman/8.0/en/installing.html

mysql频繁访问、读写配置

#BEGIN CONFIG INFO
#DESCR: 4GB RAM, InnoDB only, ACID, few connections, heavy queries
#TYPE: SYSTEM
#END CONFIG INFO

#
# This is a MySQL example config file for systems with 4GB of memory
# running mostly MySQL using InnoDB only tables and performing complex
# queries with few connections.
#
# MySQL programs look for option files in a set of
# locations which depend on the deployment platform.
# You can copy this option file to one of those
# locations. For information about these locations, see:
# http://dev.mysql.com/doc/mysql/en/option-files.html
#
# In this file, you can use all long options that a program supports.
# If you want to know which options a program supports, run the program
# with the “–help” option.
#
# More detailed information about the individual options can also be
# found in the manual.
#

#
# The following options will be read by MySQL client applications.
# Note that only client applications shipped by MySQL are guaranteed
# to read this section. If you want your own MySQL client program to
# honor these values, you need to specify it as an option during the
# MySQL client library initialization.
#
[client]
#password = [your_password]
port = 3306
socket = /tmp/mysql.sock

# *** Application-specific options follow here ***

#
# The MySQL server
#
[mysqld]

# generic configuration options
port = 3306
socket = /tmp/mysql.sock

# back_log is the number of connections the operating system can keep in
# the listen queue, before the MySQL connection manager thread has
# processed them. If you have a very high connection rate and experience
# “connection refused” errors, you might need to increase this value.
# Check your OS documentation for the maximum value of this parameter.
# Attempting to set back_log higher than your operating system limit
# will have no effect.
back_log = 50

# Don’t listen on a TCP/IP port at all. This can be a security
# enhancement, if all processes that need to connect to mysqld run
# on the same host. All interaction with mysqld must be made via Unix
# sockets or named pipes.
# Note that using this option without enabling named pipes on Windows
# (via the “enable-named-pipe” option) will render mysqld useless!
#skip-networking

# The maximum amount of concurrent sessions the MySQL server will
# allow. One of these connections will be reserved for a user with
# SUPER privileges to allow the administrator to login even if the
# connection limit has been reached.
max_connections = 100

# Maximum amount of errors allowed per host. If this limit is reached,
# the host will be blocked from connecting to the MySQL server until
# “FLUSH HOSTS” has been run or the server was restarted. Invalid
# passwords and other errors during the connect phase result in
# increasing this value. See the “Aborted_connects” status variable for
# global counter.
max_connect_errors = 10

# The number of open tables for all threads. Increasing this value
# increases the number of file descriptors that mysqld requires.
# Therefore you have to make sure to set the amount of open files
# allowed to at least 4096 in the variable “open-files-limit” in
# section [mysqld_safe]
table_open_cache = 2048

# Enable external file level locking. Enabled file locking will have a
# negative impact on performance, so only use it in case you have
# multiple database instances running on the same files (note some
# restrictions still apply!) or if you use other software relying on
# locking MyISAM tables on file level.
#external-locking

# The maximum size of a query packet the server can handle as well as
# maximum query size server can process (Important when working with
# large BLOBs). enlarged dynamically, for each connection.
max_allowed_packet = 16M

# The size of the cache to hold the SQL statements for the binary log
# during a transaction. If you often use big, multi-statement
# transactions you can increase this value to get more performance. All
# statements from transactions are buffered in the binary log cache and
# are being written to the binary log at once after the COMMIT. If the
# transaction is larger than this value, temporary file on disk is used
# instead. This buffer is allocated per connection on first update
# statement in transaction
binlog_cache_size = 1M

# Maximum allowed size for a single HEAP (in memory) table. This option
# is a protection against the accidential creation of a very large HEAP
# table which could otherwise use up all memory resources.
max_heap_table_size = 64M

# Size of the buffer used for doing full table scans.
# Allocated per thread, if a full scan is needed.
read_buffer_size = 2M

# When reading rows in sorted order after a sort, the rows are read
# through this buffer to avoid disk seeks. You can improve ORDER BY
# performance a lot, if set this to a high value.
# Allocated per thread, when needed.
read_rnd_buffer_size = 16M

# Sort buffer is used to perform sorts for some ORDER BY and GROUP BY
# queries. If sorted data does not fit into the sort buffer, a disk
# based merge sort is used instead – See the “Sort_merge_passes”
# status variable. Allocated per thread if sort is needed.
sort_buffer_size = 8M

# This buffer is used for the optimization of full JOINs (JOINs without
# indexes). Such JOINs are very bad for performance in most cases
# anyway, but setting this variable to a large value reduces the
# performance impact. See the “Select_full_join” status variable for a
# count of full JOINs. Allocated per thread if full join is found
join_buffer_size = 8M

# How many threads we should keep in a cache for reuse. When a client
# disconnects, the client’s threads are put in the cache if there aren’t
# more than thread_cache_size threads from before. This greatly reduces
# the amount of thread creations needed if you have a lot of new
# connections. (Normally this doesn’t give a notable performance
# improvement if you have a good thread implementation.)
thread_cache_size = 8

# This permits the application to give the threads system a hint for the
# desired number of threads that should be run at the same time. This
# value only makes sense on systems that support the thread_concurrency()
# function call (Sun Solaris, for example).
# You should try [number of CPUs]*(2..4) for thread_concurrency
thread_concurrency = 8

# Query cache is used to cache SELECT results and later return them
# without actual executing the same query once again. Having the query
# cache enabled may result in significant speed improvements, if your
# have a lot of identical queries and rarely changing tables. See the
# “Qcache_lowmem_prunes” status variable to check if the current value
# is high enough for your load.
# Note: In case your tables change very often or if your queries are
# textually different every time, the query cache may result in a
# slowdown instead of a performance improvement.
query_cache_size = 64M

# Only cache result sets that are smaller than this limit. This is to
# protect the query cache of a very large result set overwriting all
# other query results.
query_cache_limit = 2M

# Minimum word length to be indexed by the full text search index.
# You might wish to decrease it if you need to search for shorter words.
# Note that you need to rebuild your FULLTEXT index, after you have
# modified this value.
ft_min_word_len = 4

# If your system supports the memlock() function call, you might want to
# enable this option while running MySQL to keep it locked in memory and
# to avoid potential swapping out in case of high memory pressure. Good
# for performance.
#memlock

# Table type which is used by default when creating new tables, if not
# specified differently during the CREATE TABLE statement.
default-storage-engine = MYISAM

# Thread stack size to use. This amount of memory is always reserved at
# connection time. MySQL itself usually needs no more than 64K of
# memory, while if you use your own stack hungry UDF functions or your
# OS requires more stack for some operations, you might need to set this
# to a higher value.
thread_stack = 192K

# Set the default transaction isolation level. Levels available are:
# READ-UNCOMMITTED, READ-COMMITTED, REPEATABLE-READ, SERIALIZABLE
transaction_isolation = REPEATABLE-READ

# Maximum size for internal (in-memory) temporary tables. If a table
# grows larger than this value, it is automatically converted to disk
# based table This limitation is for a single table. There can be many
# of them.
tmp_table_size = 64M

# Enable binary logging. This is required for acting as a MASTER in a
# replication configuration. You also need the binary log if you need
# the ability to do point in time recovery from your latest backup.
log-bin=mysql-bin

# binary logging format – mixed recommended
binlog_format=mixed

# If you’re using replication with chained slaves (A->B->C), you need to
# enable this option on server B. It enables logging of updates done by
# the slave thread into the slave’s binary log.
#log_slave_updates

# Enable the full query log. Every query (even ones with incorrect
# syntax) that the server receives will be logged. This is useful for
# debugging, it is usually disabled in production use.
#log

# Print warnings to the error log file. If you have any problem with
# MySQL you should enable logging of warnings and examine the error log
# for possible explanations.
#log_warnings

# Log slow queries. Slow queries are queries which take more than the
# amount of time defined in “long_query_time” or which do not use
# indexes well, if log_short_format is not enabled. It is normally good idea
# to have this turned on if you frequently add new queries to the
# system.
slow_query_log

# All queries taking more than this amount of time (in seconds) will be
# trated as slow. Do not use “1” as a value here, as this will result in
# even very fast queries being logged from time to time (as MySQL
# currently measures time with second accuracy only).
long_query_time = 2
# *** Replication related settings
# Unique server identification number between 1 and 2^32-1. This value
# is required for both master and slave hosts. It defaults to 1 if
# “master-host” is not set, but will MySQL will not function as a master
# if it is omitted.
server-id = 1

# Replication Slave (comment out master section to use this)
#
# To configure this host as a replication slave, you can choose between
# two methods :
#
# 1) Use the CHANGE MASTER TO command (fully described in our manual) –
# the syntax is:
#
# CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>,
# MASTER_USER=<user>, MASTER_PASSWORD=<password> ;
#
# where you replace <host>, <user>, <password> by quoted strings and
# <port> by the master’s port number (3306 by default).
#
# Example:
#
# CHANGE MASTER TO MASTER_HOST=’125.564.12.1′, MASTER_PORT=3306,
# MASTER_USER=’joe’, MASTER_PASSWORD=’secret';
#
# OR
#
# 2) Set the variables below. However, in case you choose this method, then
# start replication for the first time (even unsuccessfully, for example
# if you mistyped the password in master-password and the slave fails to
# connect), the slave will create a master.info file, and any later
# changes in this file to the variable values below will be ignored and
# overridden by the content of the master.info file, unless you shutdown
# the slave server, delete master.info and restart the slaver server.
# For that reason, you may want to leave the lines below untouched
# (commented) and instead use CHANGE MASTER TO (see above)
#
# required unique id between 2 and 2^32 – 1
# (and different from the master)
# defaults to 2 if master-host is set
# but will not function as a slave if omitted
#server-id = 2
#
# The replication master for this slave – required
#master-host = <hostname>
#
# The username the slave will use for authentication when connecting
# to the master – required
#master-user = <username>
#
# The password the slave will authenticate with when connecting to
# the master – required
#master-password = <password>
#
# The port the master is listening on.
# optional – defaults to 3306
#master-port = <port>

# Make the slave read-only. Only users with the SUPER privilege and the
# replication slave thread will be able to modify data on it. You can
# use this to ensure that no applications will accidently modify data on
# the slave instead of the master
#read_only
#*** MyISAM Specific options
# Size of the Key Buffer, used to cache index blocks for MyISAM tables.
# Do not set it larger than 30% of your available memory, as some memory
# is also required by the OS to cache rows. Even if you’re not using
# MyISAM tables, you should still set it to 8-64M as it will also be
# used for internal temporary disk tables.
key_buffer_size = 32M

# MyISAM uses special tree-like cache to make bulk inserts (that is,
# INSERT … SELECT, INSERT … VALUES (…), (…), …, and LOAD DATA
# INFILE) faster. This variable limits the size of the cache tree in
# bytes per thread. Setting it to 0 will disable this optimisation. Do
# not set it larger than “key_buffer_size” for optimal performance.
# This buffer is allocated when a bulk insert is detected.
bulk_insert_buffer_size = 64M

# This buffer is allocated when MySQL needs to rebuild the index in
# REPAIR, OPTIMIZE, ALTER table statements as well as in LOAD DATA INFILE
# into an empty table. It is allocated per thread so be careful with
# large settings.
myisam_sort_buffer_size = 128M

# The maximum size of the temporary file MySQL is allowed to use while
# recreating the index (during REPAIR, ALTER TABLE or LOAD DATA INFILE.
# If the file-size would be bigger than this, the index will be created
# through the key cache (which is slower).
myisam_max_sort_file_size = 10G

# If a table has more than one index, MyISAM can use more than one
# thread to repair them by sorting in parallel. This makes sense if you
# have multiple CPUs and plenty of memory.
myisam_repair_threads = 1

# Automatically check and repair not properly closed MyISAM tables.
myisam_recover

# *** INNODB Specific options ***

# Use this option if you have a MySQL server with InnoDB support enabled
# but you do not plan to use it. This will save memory and disk space
# and speed up some things.
#skip-innodb

# Additional memory pool that is used by InnoDB to store metadata
# information. If InnoDB requires more memory for this purpose it will
# start to allocate it from the OS. As this is fast enough on most
# recent operating systems, you normally do not need to change this
# value. SHOW INNODB STATUS will display the current amount used.
innodb_additional_mem_pool_size = 16M

# InnoDB, unlike MyISAM, uses a buffer pool to cache both indexes and
# row data. The bigger you set this the less disk I/O is needed to
# access data in tables. On a dedicated database server you may set this
# parameter up to 80% of the machine physical memory size. Do not set it
# too large, though, because competition of the physical memory may
# cause paging in the operating system. Note that on 32bit systems you
# might be limited to 2-3.5G of user level memory per process, so do not
# set it too high.
innodb_buffer_pool_size = 2G

# InnoDB stores data in one or more data files forming the tablespace.
# If you have a single logical drive for your data, a single
# autoextending file would be good enough. In other cases, a single file
# per device is often a good choice. You can configure InnoDB to use raw
# disk partitions as well – please refer to the manual for more info
# about this.
innodb_data_file_path = ibdata1:10M:autoextend

# Set this option if you would like the InnoDB tablespace files to be
# stored in another location. By default this is the MySQL datadir.
#innodb_data_home_dir = <directory>

# Number of IO threads to use for async IO operations. This value is
# hardcoded to 8 on Unix, but on Windows disk I/O may benefit from a
# larger number.
innodb_write_io_threads = 8
innodb_read_io_threads = 8

# If you run into InnoDB tablespace corruption, setting this to a nonzero
# value will likely help you to dump your tables. Start from value 1 and
# increase it until you’re able to dump the table successfully.
#innodb_force_recovery=1

# Number of threads allowed inside the InnoDB kernel. The optimal value
# depends highly on the application, hardware as well as the OS
# scheduler properties. A too high value may lead to thread thrashing.
innodb_thread_concurrency = 16

# If set to 1, InnoDB will flush (fsync) the transaction logs to the
# disk at each commit, which offers full ACID behavior. If you are
# willing to compromise this safety, and you are running small
# transactions, you may set this to 0 or 2 to reduce disk I/O to the
# logs. Value 0 means that the log is only written to the log file and
# the log file flushed to disk approximately once per second. Value 2
# means the log is written to the log file at each commit, but the log
# file is only flushed to disk approximately once per second.
innodb_flush_log_at_trx_commit = 1

# Speed up InnoDB shutdown. This will disable InnoDB to do a full purge
# and insert buffer merge on shutdown. It may increase shutdown time a
# lot, but InnoDB will have to do it on the next startup instead.
#innodb_fast_shutdown

# The size of the buffer InnoDB uses for buffering log data. As soon as
# it is full, InnoDB will have to flush it to disk. As it is flushed
# once per second anyway, it does not make sense to have it very large
# (even with long transactions).
innodb_log_buffer_size = 8M

# Size of each log file in a log group. You should set the combined size
# of log files to about 25%-100% of your buffer pool size to avoid
# unneeded buffer pool flush activity on log file overwrite. However,
# note that a larger logfile size will increase the time needed for the
# recovery process.
innodb_log_file_size = 256M

# Total number of files in the log group. A value of 2-3 is usually good
# enough.
innodb_log_files_in_group = 3

# Location of the InnoDB log files. Default is the MySQL datadir. You
# may wish to point it to a dedicated hard drive or a RAID1 volume for
# improved performance
#innodb_log_group_home_dir

# Maximum allowed percentage of dirty pages in the InnoDB buffer pool.
# If it is reached, InnoDB will start flushing them out agressively to
# not run out of clean pages at all. This is a soft limit, not
# guaranteed to be held.
innodb_max_dirty_pages_pct = 90

# The flush method InnoDB will use for Log. The tablespace always uses
# doublewrite flush logic. The default value is “fdatasync”, another
# option is “O_DSYNC”.
#innodb_flush_method=O_DSYNC

# How long an InnoDB transaction should wait for a lock to be granted
# before being rolled back. InnoDB automatically detects transaction
# deadlocks in its own lock table and rolls back the transaction. If you
# use the LOCK TABLES command, or other transaction-safe storage engines
# than InnoDB in the same transaction, then a deadlock may arise which
# InnoDB cannot notice. In cases like this the timeout is useful to
# resolve the situation.
innodb_lock_wait_timeout = 120
[mysqldump]
# Do not buffer the whole result set in memory before writing it to
# file. Required for dumping very large tables
quick

max_allowed_packet = 16M

[mysql]
no-auto-rehash

# Only allow UPDATEs and DELETEs that use keys.
#safe-updates

[myisamchk]
key_buffer_size = 512M
sort_buffer_size = 512M
read_buffer = 8M
write_buffer = 8M

[mysqlhotcopy]
interactive-timeout

[mysqld_safe]
# Increase the amount of open files allowed per process. Warning: Make
# sure you have set the global system limit high enough! The high value
# is required for a large number of opened tables
open-files-limit = 8192

Nginx负载均衡策略

负载均衡用于从“upstream”模块定义的后端服务器列表中选取一台服务器接受用户的请求。一个最基本的upstream模块是这样的,模块内的server是服务器列表:

    #动态服务器组
    upstream dynamic_zuoyu {
        server localhost:8080;  #tomcat 7.0
        server localhost:8081;  #tomcat 8.0
        server localhost:8082;  #tomcat 8.5
        server localhost:8083;  #tomcat 9.0
    }

在upstream模块配置完成后,要让指定的访问反向代理到服务器列表:

        #其他页面反向代理到tomcat容器
        location ~ .*$ {
            index index.jsp index.html;
            proxy_pass http://dynamic_zuoyu;
        }

这就是最基本的负载均衡实例,但这不足以满足实际需求;目前Nginx服务器的upstream模块支持6种方式的分配:

轮询 默认方式
weight 权重方式
ip_hash 依据ip分配方式
least_conn 最少连接方式
fair(第三方) 响应时间方式
url_hash(第三方) 依据URL分配方式

在这里,只详细说明Nginx自带的负载均衡策略,第三方不多描述。

1、轮询

最基本的配置方法,上面的例子就是轮询的方式,它是upstream模块默认的负载均衡默认策略。每个请求会按时间顺序逐一分配到不同的后端服务器。

有如下参数:

fail_timeout 与max_fails结合使用。
max_fails
设置在fail_timeout参数设置的时间内最大失败次数,如果在这个时间内,所有针对该服务器的请求都失败了,那么认为该服务器会被认为是停机了,
fail_time 服务器会被认为停机的时间长度,默认为10s。
backup 标记该服务器为备用服务器。当主服务器停止时,请求会被发送到它这里。
down 标记服务器永久停机了。

注意:

  • 在轮询中,如果服务器down掉了,会自动剔除该服务器。
  • 缺省配置就是轮询策略。
  • 此策略适合服务器配置相当,无状态且短平快的服务使用。

2、weight

权重方式,在轮询策略的基础上指定轮询的几率。例子如下:

    #动态服务器组
    upstream dynamic_zuoyu {
        server localhost:8080   weight=2;  #tomcat 7.0
        server localhost:8081;  #tomcat 8.0
        server localhost:8082   backup;  #tomcat 8.5
        server localhost:8083   max_fails=3 fail_timeout=20s;  #tomcat 9.0
    }

在该例子中,weight参数用于指定轮询几率,weight的默认值为1,;weight的数值与访问比率成正比,比如Tomcat 7.0被访问的几率为其他服务器的两倍。

注意:

  • 权重越高分配到需要处理的请求越多。
  • 此策略可以与least_conn和ip_hash结合使用。
  • 此策略比较适合服务器的硬件配置差别比较大的情况。

3、ip_hash

指定负载均衡器按照基于客户端IP的分配方式,这个方法确保了相同的客户端的请求一直发送到相同的服务器,以保证session会话。这样每个访客都固定访问一个后端服务器,可以解决session不能跨服务器的问题。

#动态服务器组
    upstream dynamic_zuoyu {
        ip_hash;    #保证每个访客固定访问一个后端服务器
        server localhost:8080   weight=2;  #tomcat 7.0
        server localhost:8081;  #tomcat 8.0
        server localhost:8082;  #tomcat 8.5
        server localhost:8083   max_fails=3 fail_timeout=20s;  #tomcat 9.0
    }

注意:

  • 在nginx版本1.3.1之前,不能在ip_hash中使用权重(weight)。
  • ip_hash不能与backup同时使用。
  • 此策略适合有状态服务,比如session。
  • 当有服务器需要剔除,必须手动down掉。

4、least_conn

把请求转发给连接数较少的后端服务器。轮询算法是把请求平均的转发给各个后端,使它们的负载大致相同;但是,有些请求占用的时间很长,会导致其所在的后端负载较高。这种情况下,least_conn这种方式就可以达到更好的负载均衡效果。

    #动态服务器组
    upstream dynamic_zuoyu {
        least_conn;    #把请求转发给连接数较少的后端服务器
        server localhost:8080   weight=2;  #tomcat 7.0
        server localhost:8081;  #tomcat 8.0
        server localhost:8082 backup;  #tomcat 8.5
        server localhost:8083   max_fails=3 fail_timeout=20s;  #tomcat 9.0
    }

注意:

  • 此负载均衡策略适合请求处理时间长短不一造成服务器过载的情况。

5、第三方策略

第三方的负载均衡策略的实现需要安装第三方插件。

①fair

按照服务器端的响应时间来分配请求,响应时间短的优先分配。

    #动态服务器组
    upstream dynamic_zuoyu {
        server localhost:8080;  #tomcat 7.0
        server localhost:8081;  #tomcat 8.0
        server localhost:8082;  #tomcat 8.5
        server localhost:8083;  #tomcat 9.0
        fair;    #实现响应时间短的优先分配
    }

②url_hash

按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,要配合缓存命中来使用。同一个资源多次请求,可能会到达不同的服务器上,导致不必要的多次下载,缓存命中率不高,以及一些资源时间的浪费。而使用url_hash,可以使得同一个url(也就是同一个资源请求)会到达同一台服务器,一旦缓存住了资源,再此收到请求,就可以从缓存中读取。

    #动态服务器组
    upstream dynamic_zuoyu {
        hash $request_uri;    #实现每个url定向到同一个后端服务器
        server localhost:8080;  #tomcat 7.0
        server localhost:8081;  #tomcat 8.0
        server localhost:8082;  #tomcat 8.5
        server localhost:8083;  #tomcat 9.0
    }
11314151617114
 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |