2006年02月28日

1.获取当前配置参数

要优化配置参数,首先要了解当前的配置参数以及运行情况。使用下列命令可以获得目前服务器使用的配置参数:

mysqld –verbose –help

mysqladmin variables extended-status –u root –p

在MySQL控制台里面,运行下列命令可以获取状态变量的值:

mysql> SHOW STATUS;

如果只要检查某几个状态变量,可以使用下列命令:

mysql> SHOW STATUS LIKE ‘[匹配模式]’; ( 可以使用%、?等 )

2.优化参数

参数优化基于一个前提,就是在我们的数据库中通常都使用InnoDB表,而不使用MyISAM表。在优化MySQL时,有两个配置参数是最重要的,即table_cachekey_buffer_size

table_cache

table_cache指定表高速缓存的大小。每当MySQL访问一个表时,如果在表缓冲区中还有空间,该表就被打开并放入其中,这样可以更快地访问表内容。通过检查峰值时间的状态值Open_tablesOpened_tables,可以决定是否需要增加table_cache的值。如果你发现open_tables等于table_cache,并且opened_tables在不断增长,那么你就需要增加table_cache的值了(上述状态值可以使用SHOW STATUS LIKE ‘Open%tables’获得)。注意,不能盲目地把table_cache设置成很大的值。如果设置得太高,可能会造成文件描述符不足,从而造成性能不稳定或者连接失败。

对于有1G内存的机器,推荐值是128256

案例1:该案例来自一个不是特别繁忙的服务器

table_cache – 512

open_tables – 103

opened_tables – 1273

uptime – 4021421 (measured in seconds)

该案例中table_cache似乎设置得太高了。在峰值时间,打开表的数目比table_cache要少得多。

案例2:该案例来自一台开发服务器。

table_cache – 64

open_tables – 64

opened-tables – 431

uptime – 1662790 (measured in seconds)

虽然open_tables已经等于table_cache,但是相对于服务器运行时间来说,opened_tables的值也非常低。因此,增加table_cache的值应该用处不大。

案例3:该案例来自一个upderperforming的服务器

table_cache – 64

open_tables – 64

opened_tables – 22423

uptime – 19538

该案例中table_cache设置得太低了。虽然运行时间不到6小时,open_tables达到了最大值,opened_tables的值也非常高。这样就需要增加table_cache的值。

key_buffer_size

key_buffer_size指定索引缓冲区的大小,它决定索引处理的速度,尤其是索引读的速度。通过检查状态值Key_read_requestsKey_reads,可以知道key_buffer_size设置是否合理。比例key_reads / key_read_requests应该尽可能的低,至少是1:100,1:1000更好(上述状态值可以使用SHOW STATUS LIKE ‘key_read%’获得)。

key_buffer_size只对MyISAM表起作用。即使你不使用MyISAM表,但是内部的临时磁盘表是MyISAM表,也要使用该值。可以使用检查状态值created_tmp_disk_tables得知详情。

对于1G内存的机器,如果不使用MyISAM表,推荐值是16M8-64M)。

案例1:健康状况

key_buffer_size – 402649088 (384M)

key_read_requests – 597579931

key_reads – 56188

案例2:警报状态

key_buffer_size – 16777216 (16M)

key_read_requests – 597579931

key_reads – 53832731

案例1中比例低于1:10000,是健康的情况;案例2中比例达到1:11,警报已经拉响。

优化query_cache_size

从4.0.1开始,MySQL提供了查询缓冲机制。使用查询缓冲,MySQL将SELECT语句和查询结果存放在缓冲区中,今后对于同样的SELECT语句(区分大小写),将直接从缓冲区中读取结果。根据MySQL用户手册,使用查询缓冲最多可以达到238%的效率。

通过检查状态值Qcache_*,可以知道query_cache_size设置是否合理(上述状态值可以使用SHOW STATUS LIKE ‘Qcache%’获得)。如果Qcache_lowmem_prunes的值非常大,则表明经常出现缓冲不够的情况,如果Qcache_hits的值也非常大,则表明查询缓冲使用非常频繁,此时需要增加缓冲大小;如果Qcache_hits的值不大,则表明你的查询重复率很低,这种情况下使用查询缓冲反而会影响效率,那么可以考虑不用查询缓冲。此外,在SELECT语句中加入SQL_NO_CACHE可以明确表示不使用查询缓冲。

与查询缓冲有关的参数还有query_cache_typequery_cache_limitquery_cache_min_res_unitquery_cache_type指定是否使用查询缓冲,可以设置为0、1、2,该变量是SESSION级的变量。query_cache_limit指定单个查询能够使用的缓冲区大小,缺省为1M。query_cache_min_res_unit是在4.1版本以后引入的,它指定分配缓冲区空间的最小单位,缺省为4K。检查状态值Qcache_free_blocks,如果该值非常大,则表明缓冲区中碎片很多,这就表明查询结果都比较小,此时需要减小query_cache_min_res_unit

开启二进制日志( Binary Log )

二进制日志包含所有更新数据的语句,其目的是在恢复数据库时用它来把数据尽可能恢复到最后的状态。另外,如果做同步复制( Replication )的话,也需要使用二进制日志传送修改情况。

开启二进制日志,需要设置参数log-binlog_bin指定日志文件,如果不提供文件名,MySQL将自己产生缺省文件名。MySQL会在文件名后面自动添加数字索引,每次启动服务时,都会重新生成一个新的二进制文件。

此外,使用log-bin-index可以指定索引文件;使用binlog-do-db可以指定记录的数据库;使用binlog-ignore-db可以指定不记录的数据库。注意的是:binlog-do-dbbinlog-ignore-db一次只指定一个数据库,指定多个数据库需要多个语句。而且,MySQL会将所有的数据库名称改成小写,在指定数据库时必须全部使用小写名字,否则不会起作用。

在MySQL中使用SHOW MASTER STATUS命令可以查看目前的二进制日志状态。

开启慢查询日志( slow query log )

慢查询日志对于跟踪有问题的查询非常有用。它记录所有查过long_query_time的查询,如果需要,还可以记录不使用索引的记录。下面是一个慢查询日志的例子:

<formulas /> 开启慢查询日志,需要设置参数log_slow_querieslong_query_timeslog-queries-not-using-indexeslog_slow_queries指定日志文件,如果不提供文件名,MySQL将自己产生缺省文件名。long_query_times指定慢查询的阈值,缺省是10秒。log-queries-not-using-indexes是4.1.0以后引入的参数,它指示记录不使用索引的查询。

配置InnoDB

相对于MyISAM表来说,正确配置参数对于InnoDB表更加关键。其中,最重要的参数是innodb_data_file_path。它指定表数据和索引存储的空间,可以是一个或者多个文件。最后一个数据文件必须是自动扩充的,也只有最后一个文件允许自动扩充。这样,当空间用完后,自动扩充数据文件就会自动增长(以8MB为单位)以容纳额外的数据。例如:

innodb_data_file_path=/disk1/ibdata1:900M;/disk2/ibdata2:50M:autoextend

两个数据文件放在不同的磁盘上。数据首先放在ibdata1中,当达到900M以后,数据就放在ibdata2中。一旦达到50MB,ibdata2将以8MB为单位自动增长。

如果磁盘满了,你需要在另外的磁盘上面增加一个数据文件。为此,你需要查看最后一个文件的尺寸,然后计算最接近的整数(MB)。然后手工修改该文件的大小,并添加新的数据文件。例如:假设ibdata2已经有109MB数据,那么可以修改如下:

innodb_data_file_path=/disk1/ibdata1:900M;/disk2/ibdata2:109M;/disk3/ibdata3:500M:autoextend

flush_time

如果系统有问题并且经常锁死或重新引导,应将该变量设置为非零值,这将导致服务器按flush_time 秒来刷新表的高速缓存。用这种方法来写出对表的修改将降低性能,但可减少表讹误或数据丢失的机会。

一般使用缺省值。

Binlog_cache_size

The size of the cache to hold the SQL statements for the binary log during a transaction. A binary log cache is allocated for each client if the server supports any transactional storage engines and if the server has binary log enabled(–log-bin option). If you often use big, multiple-statement transactions, you can increase this to get more performance. The Binlog_cache_use and Binlog_cache_disk_use status variables can be useful for tuning the size of this variable.

3.存储引擎

在MYSQL 3.23.0版本中,引入了MyISAM存储引擎。它是一个非事务型的存储引擎,成为了MYSQL的缺省存储引擎。但是,如果使用设置向导来设置参数,则它会把InnoDB作为缺省的存储引擎。InnoDB是一个事务型的存储引擎。

创建表的时候,可以为表指定存储引擎,语法如下:

CREATE TABLE t (i INT) ENGINE = MyISAM

CREATE TABLE t (i INT) TYPE = MyISAM

如果没有指定,则使用缺省的存储引擎。也可以使用ALTER TABLE来更换表引擎,语法如下:

ALTER TABLE t ENGINE = MyISAM

同一数据库中可以包含不同存储引擎的表。

事务型表具有以下特点:

Ø        Safer. Even if MySQL crashes or you get hardware problems, you can get your data back, either by automatic
2006年02月23日

通常的网页缓存方式有动态缓存和静态缓存等几种,在ASP.NET中已经可以实现对页面局部进行缓存,而使用memcached的缓存比ASP.NET的局部缓存更加灵活,可以缓存任意的对象,不管是否在页面上输出。而memcached最大的优点是可以分布式的部署,这对于大规模应用来说也是必不可少的要求。
LiveJournal.com使用了memcached在前端进行缓存,取得了良好的效果,而像wikipedia,sourceforge等也采用了或即将采用memcached作为缓存工具。memcached可以大规模网站应用发挥巨大的作用。

Memcached是什么?

Memcached是高性能的,分布式的内存对象缓存系统,用于在动态应用中减少数据库负载,提升访问速度。
Memcached由Danga Interactive开发,用于提升LiveJournal.com访问速度的。LJ每秒动态页面访问量几千次,用户700万。Memcached将数据库负载大幅度降低,更好的分配资源,更快速访问。


如何使用memcached-Server端?

在服务端运行:
# ./memcached -d -m 2048 -l 10.0.0.40 -p 11211
这将会启动一个占用2G内存的进程,并打开11211端口用于接收请求。由于32位系统只能处理4G内存的寻址,所以在大于4G内存使用PAE的32位服务器上可以运行2-3个进程,并在不同端口进行监听。


如何使用memcached-Client端?

在应用端包含一个用于描述Client的Class后,就可以直接使用,非常简单。
PHP Example:
$options["servers"] = array("192.168.1.41:11211", "192.168.1.42:11212");
$options["debug"] = false;
$memc = new MemCachedClient($options);
$myarr = array("one","two", 3);
$memc->set("key_one", $myarr);
$val = $memc->get("key_one");
print $val[0]."\n"; // prints ‘one‘
print $val[1]."\n"; // prints ‘two‘
print $val[2]."\n"; // prints 3


为什么不使用数据库做这些?


暂且不考虑使用什么样的数据库(MS-SQL, Oracle, Postgres, MysQL-InnoDB, etc..), 实现事务(ACID,Atomicity, Consistency, Isolation, and Durability )需要大量开销,特别当使用到硬盘的时候,这就意味着查询可能会阻塞。当使用不包含事务的数据库(例如Mysql-MyISAM),上面的开销不存在,但读线程又可能会被写线程阻塞。
Memcached从不阻塞,速度非常快。


为什么不使用共享内存?

最初的缓存做法是在线程内对对象进行缓存,但这样进程间就无法共享缓存,命中率非常低,导致缓存效率极低。后来出现了共享内存的缓存,多个进程或者线程共享同一块缓存,但毕竟还是只能局限在一台机器上,多台机器做相同的缓存同样是一种资源的浪费,而且命中率也比较低。
Memcached Server和Clients共同工作,实现跨服务器分布式的全局的缓存。并且可以与Web Server共同工作,Web Server对CPU要求高,对内存要求低,Memcached Server对CPU要求低,对内存要求高,所以可以搭配使用。


Mysql 4.x的缓存怎么样?

Mysql查询缓存不是很理想,因为以下几点:
当指定的表发生更新后,查询缓存会被清空。在一个大负载的系统上这样的事情发生的非常频繁,导致查询缓存效率非常低,有的情况下甚至还不如不开,因为它对cache的管理还是会有开销。
在32位机器上,Mysql对内存的操作还是被限制在4G以内,但memcached可以分布开,内存规模理论上不受限制。
Mysql上的是查询缓存,而不是对象缓存,如果在查询后还需要大量其它操作,查询缓存就帮不上忙了。
如果要缓存的数据不大,并且查询的不是非常频繁,这样的情况下可以用Mysql 查询缓存,不然的话memcached更好。


数据库同步怎么样?

这里的数据库同步是指的类似Mysql Master-Slave模式的靠日志同步实现数据库同步的机制。
你可以分布读操作,但无法分布写操作,但写操作的同步需要消耗大量的资源,而且这个开销是随着slave服务器的增长而不断增长的。
下一步是要对数据库进行水平切分,从而让不同的数据分布到不同的数据库服务器组上,从而实现分布的读写,这需要在应用中实现根据不同的数据连接不同的数据库。
当这一模式工作后(我们也推荐这样做),更多的数据库导致更多的让人头疼的硬件错误。
Memcached可以有效的降低对数据库的访问,让数据库用主要的精力来做不频繁的写操作,而这是数据库自己控制的,很少会自己阻塞 自己。


Memcached快吗?


非常快,它使用libevent,可以应付任意数量打开的连接(使用epoll,而非poll),使用非阻塞网络IO,分布式散列对象到不同的服务器,查询复杂度是O(1)。

英文资料参考:

http://www.linuxjournal.com/article/7451
http://www.danga.com/

Query Cache 在提高数据库性能方面具有非常重要的作用。

其设定也非常简单,仅需要在配置文件写入两行: query_cache_type 和 query_cache _size,而且 MySQL 的 query cache 非常快!而且一旦命中,就直接发送给客户端,节约大量的 CPU 时间。

当然,非 SELECT 语句对缓冲是有影响的,它们可能使缓冲中的数据过期。一个 UPDATE 语句引起的部分表修改,将导致对该表所有的缓冲数据失效,这是 MySQL 为了平衡性能而没有采取的措施。因为,如果每次 UPDATE 需要检查修改的数据,然后撤出部分缓冲将导致代码的复杂度增加。



query_cache_type 0 代表不使用缓冲, 1 代表使用缓冲,2 代表根据需要使用。

设置 1 代表缓冲永远有效,如果不需要缓冲,就需要使用如下语句:

SELECT SQL_NO_CACHE * FROM my_table WHERE …

如果设置为 2 ,需要开启缓冲,可以用如下语句:

SELECT SQL_CACHE * FROM my_table WHERE …

用 SHOW STATUS 可以查看缓冲的情况:

mysql> show status like ‘Qca%’;
+————————-+———-+
| Variable_name | Value |
+————————-+———-+
| Qcache_queries_in_cache | 8 |
| Qcache_inserts | 545875 |
| Qcache_hits | 83951 |
| Qcache_lowmem_prunes | 0 |
| Qcache_not_cached | 2343256 |
| Qcache_free_memory | 33508248 |
| Qcache_free_blocks | 1 |
| Qcache_total_blocks | 18 |
+————————-+———-+
8 rows in set (0.00 sec)

如果需要计算命中率,需要知道服务器执行了多少 SELECT 语句:

mysql> show status like ‘Com_sel%’;
+—————+———+
| Variable_name | Value |
+—————+———+
| Com_select | 2889628 |
+—————+———+
1 row in set (0.01 sec)

在本例中, MySQL 命中了 2,889,628 条查询中的 83,951 条,而且 INSERT 语句只有 545,875 条。因此,它们两者的和和280万的总查询相比有很大差距,因此,我们知道本例使用的缓冲类型是 2 。


而在类型是 1 的例子中, Qcache_hits 的数值会远远大于 Com_select 。

代码片段如下:

$_pst = file_get_contents("php://input");

$_a = explode(‘&’,urldecode($_pst));

$i = 0;

$photoURL = array();

while($i < count($_a))

{

    $_b = split(‘=’, $_a[$i]);

     if(‘xxxx’ == $_b[0])

     {

        if(empty($_b[1]))

        {

            die("error occurs!" );

         }

         $xxxx[]=$_b[1];

    }

    $i++;

}

PHP 输入/输出流

PHP 3.0.13 及以上版本,自 PHP 4.3.0 起支持 php://outputphp://input,自 PHP 5.0.0 起支持 php://filter
  • php://stdin
  • php://stdout
  • php://stderr
  • php://output
  • php://input
  • php://filter
php://stdinphp://stdoutphp://stderr 允许访问 PHP 进程相应的输入或者输出流。
php://output 允许向输出缓冲机制写入数据,和 print()echo() 的方式相同。
php://input 允许您读取 POST 的原始数据。 和 $HTTP_RAW_POST_DATA 比起来,它给内存带来的压力较小,并且不需要任何特殊的 php.ini 设置。
php://stdinphp://input 是只读的,同时,php://stdoutphp://stderrphp://output 是只写的。
php://filter 是一种设计用来允许过滤器程序在打开时成为流的封装协议。这对于单独具有完整功能的文件函数例如 readfile()file()file_get_contents() 很有用,否则就没有机会在读取内容之前将过滤器应用于流之上。
php://filter 的目标接受随后的’参数’作为其’路径’的一部分。
  • /resource=<stream to be filtered> (required) 此参数必须位于 php://filter 的末尾并且需要指向向要过滤的流。

    <?php
    /* This is equivalent to simply:
      readfile("http://www.example.com");
       since no filters are actually specified */

    readfile("php://filter/resource=http://www.example.com");
    ?>
  • /read=<filter list to apply to read chain> (optional) 本参数接受一个或多个过滤器的名字,用管道字符 | 分隔。

    <?php
    /* This will output the contents of
       www.example.com entirely in uppercase */
    readfile("php://filter/read=string.toupper/resource=http://www.example.com");

    /* This will do the same as above
       but will also ROT13 encode it */
    readfile("php://filter/read=string.toupper|string.rot13/resource=http://www.example.com");
    ?>
  • /write=<filter list to apply to write chain> (optional) 本参数接受一个或多个过滤器的名字,用管道字符 | 分隔。

    <?php
    /* This will filter the string "Hello World"
       through the rot13 filter, then write to
       example.txt in the current directory */
    file_set_contents("php://filter/write=string.rot13/resource=example.txt","Hello World");
    ?>
  • /<filter list to apply to both chains> (optional) 任何没有被 read=write= 指定的过滤器会被同时应用于读写链。
表格 I-5. Wrapper Summary (For php://filter, refer to summary of wrapper being filtered.)
属性 支持
Restricted by allow_url_fopen. No
Allows Reading php://stdin and php://input only.
Allows Writing php://stdout, php://stderr, and php://output only.
Allows Appending php://stdout, php://stderr, and php://output only. (Equivalent to writing)
Allows Simultaneous Reading and Writing No. These wrappers are unidirectional.
Supports stat() No
Supports unlink() No
2006年01月25日

my.cnf完整內容:

CODE:
[Copy to clipboard]
# MySQL Server Instance Configuration File
# ———————————————————————-
# Generated by the MySQL Server Instance Configuration Wizard
#
#
# Installation Instructions
# ———————————————————————-
#
# On Linux you can copy this file to /etc/my.cnf to set global options,
# mysql-data-dir/my.cnf to set server-specific options
# (@localstatedir@ for this installation) or to
# ~/.my.cnf to set user-specific options.
#
# On Windows you should keep this file in the installation directory
# of your server (e.g. C:\Program Files\MySQL\MySQL Server 4.1). To
# make sure the server reads the config file use the startup option
# "–defaults-file".
#
# To run run the server from the command line, execute this in a
# command line shell, e.g.
# mysqld –defaults-file="C:\Program Files\MySQL\MySQL Server 4.1\my.ini"
#
# To install the server as a Windows service manually, execute this in a
# command line shell, e.g.
# mysqld –install MySQL41 –defaults-file="C:\Program Files\MySQL\MySQL Server 4.1\my.ini"
#
# And then execute this in a command line shell to start the server, e.g.
# net start MySQL41
#
#
# Guildlines for editing this file
# ———————————————————————-
#
# In this file, you can use all long options that the program supports.
# If you want to know the options a program supports, start the program
# with the "–help" option.
#
# More detailed information about the individual options can also be
# found in the manual.
#
#
# CLIENT SECTION
# ———————————————————————-
#
# 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]

port=3333

[mysql]

default-character-set=gb2312


# SERVER SECTION
# ———————————————————————-
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this
# file.
#
[mysqld]

# The TCP/IP Port the MySQL Server will listen on
port=3333


#Path to installation directory. All paths are usually resolved relative to this.
basedir="C:/MySQL/"

#Path to the database root
datadir="C:/MySQL/Data/"

# The default character set that will be used when a new schema or table is
# created and no character set is defined
default-character-set=gb2312

# The default storage engine that will be used when create new tables when
default-storage-engine=INNODB

# Set the SQL mode to strict
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

# 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=255

# 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=8M

# 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_cache=510

# 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=13M


# 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=12

#*** MyISAM Specific options

# 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=100G

# If the temporary file used for fast index creation would be bigger
# than using the key cache by the amount specified here, then prefer the
# key cache method.  This is mainly used to force long character keys in
# large tables to use the slower key cache method to create the index.
myisam_max_extra_sort_file_size=100G

# If the temporary file used for fast index creation would be bigger
# than using the key cache by the amount specified here, then prefer the
# key cache method.  This is mainly used to force long character keys in
# large tables to use the slower key cache method to create the index.
myisam_sort_buffer_size=8M

# 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=8M

# Size of the buffer used for doing full table scans of MyISAM tables.
# Allocated per thread, if a full scan is needed.
read_buffer_size=64K
read_rnd_buffer_size=256K

# This buffer is allocated when MySQL needs to rebuild the index in
# REPAIR, OPTIMZE, 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.
sort_buffer_size=203K


#*** INNODB Specific options ***
innodb_data_home_dir="C:/Data/"

# 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=2M

# 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

# 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=1M

# 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=31M

# 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=10M

# 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=8

mysql从 3.23.42 开始,InnoDB 包括了 InnoDB 监视器,能输出InnoDB 内部状态的信息,这些数据在性能调优时十分有用,当打开时,监视器能每15秒在服务器端输出数据到标准输出,如果不是从命令行启动的话,这些输出会写入到 .err 文件中,在 Windows 平台上,必须在 DOS 命令行下以 –standalone –console 参数启动。

主要信息包括:

每个激活的事务锁住的表以及记录
事务的锁等待
线程的信号等待
延迟的文件 i/o 请求
缓冲池统计以及删除和插入缓冲合并的活动

启动的命令为:

CREATE TABLE innodb_monitor(a int) type = innodb;

停止的语法是:
DROP TABLE innodb_monitor;

如果数据库关闭时,监视器还在运行,下次启动监视器前必须先关闭。

用同样的语法你可以启动 innodb_lock_monitor 以及 innodb_tablespace_monitor

2006年01月19日

之前写了一个简单的MGM node上的config.ini的说明.这里把整个配置方法补充完成.

在MySQL Cluster中,我们需要每个node/host上都要写1个configuration文件.
• 每个data node or SQL node都需要有一个my.cnf文件, 其中包含了2条有用的连接信息:
一个connectstring告诉节点去何处寻找MGM node,还有一个告诉MySQL server 在本机上运行NDB模式.

•management node需要一个config.ini文件,记载了他需要维护多少个replicas,在每个data node上,需要给data和indexes分配多少内存,去何处寻找data nodes,每个data node上要把data存放在何处,去何处发现任何的SQL nodes.

配置Storage node和SQL Nodes

data nodes 的my.cnf 相当简单. 该文件应该位于/etc目录,并且可以很简单的编辑,例如:

vi /etc/my.cnf

每个data node和SQL node上的my.cnf应该如下所写:

# Options for mysqld process:
[MYSQLD]
ndbcluster # run NDB engine
ndb-connectstring=192.168.0.10 # location of MGM node

# Options for ndbd process:
[MYSQL_CLUSTER]
ndb-connectstring=192.168.0.10 # location of MGM node

配置Management Node

配置MGM node首先:(running as root):
mkdir /var/lib/mysql-cluster
cd /var/lib/mysql-cluster
vi config.ini

config.ini 文件的推荐设置如下:

# Options affecting ndbd processes on all data nodes:
[NDBD DEFAULT]
NoOfReplicas=2 # Number of replicas
DataMemory=80M # How much memory to allocate for data storage
IndexMemory=18M # How much memory to allocate for index storage

# For DataMemory and IndexMemory, we have used the
# default values. Since the "world" database takes up
# only about 500KB, this should be more than enough for
# this example Cluster setup.

# TCP/IP options:
[TCP DEFAULT]
portnumber=2202 # This the default; however, you can use any
# port that is free for all the hosts in cluster
# Note: It is recommended beginning with MySQL 5.0 that
MySQL Cluster
# you do not specify the portnumber at all and simply allow
# the default value to be used instead

# Management process options:
[NDB_MGMD]
hostname=192.168.0.10 # Hostname or IP address of MGM node
datadir=/var/lib/mysql-cluster # Directory for MGM node logfiles

# Options for data node "A":

[NDBD]
# (one [NDBD] section per data node)
hostname=192.168.0.30 # Hostname or IP address
datadir=/usr/local/mysql/data # Directory for this data node’s datafiles


# Options for data node "B":
[NDBD]
hostname=192.168.0.40 # Hostname or IP address
datadir=/usr/local/mysql/data # Directory for this data node’s datafiles

# SQL node options:
[MYSQLD]
hostname=192.168.0.20 # Hostname or IP address
# (additional mysqld connections can be
# specified for this node for various
# purposes such as running ndb_restore)
(NOTE: The "world" database can be downloaded from http://dev.mysql.com/doc/ where it can be
found listed under "Examples".)

Once all the configuration files have been created and these minimal options have been specified,
you are ready to proceed with starting the cluster and verifying that all processes are running.

Note: The default port for Cluster management nodes is 1186; the default port for data nodes is
2202. Beginning with MySQL 5.0.3, this restriction is lifted, and the cluster will automatically allocate
ports for data nodes from those that are already free.

apache限制并发数,IP,带宽设置

限制并发数
下载模块:

到官方网址: http://www.nowhere-land.org/programs/mod_vhost_limit/下载模块

http://www.nowhere-land.org/programs/mod_vhost_limit/mod_vhost_limit-0.4.tar.gz

安装:
apxs -c mod_vhost_limit.c -o /path/to/libexec/mod_vhost_limit.so

在 httpd.conf 加入:

LoadModule vhost_limit_module libexec/mod_vhost_limit.so
AddModule mod_vhost_limit.c

配置:

MaxClients 150
ExtendedStatus On

NameVirtualHost *

<VIRTUALHOST * />
    ServerName       server1
    DocumentRoot     /some/where/1
    MaxVhostClients  100


<VIRTUALHOST * />
    ServerName       server2
    DocumentRoot     /some/where/2
    MaxVhostClients  30


<VIRTUALHOST * />
    ServerName       server3
    DocumentRoot     /some/where/3


其中: server1 被限制为 100 个并发线程数。 server2 被限制为 30 个并发线程数。 server3 没有被限制。

注:需 mod_status 的 ExtendedStatus On 支持!!

如超出限制的并发数在客户端就会出现503错误 
———————————————————————————————-

限制IP连接数

到这里下载模块 http://dominia.org/djao/limit/mod_limitipconn-0.04.tar.gz

安装:
tar zxvf mod_limitipconn-0.04.tar.gz
cd mod_limitipconn-0.04
make APXS=/usr/local/apache/bin/apxs  ß—–这里要按你自己的路径设置
make install APXS=/usr/local/apache/bin/apxs ß—–这里要按你自己的路径设置

编辑httpd.conf
添加
全局变量:
  < IfModule mod_limitipconn.c >
      < Location / >   # 所有虚拟主机的/目录
          MaxConnPerIP 3     # 每IP只允许3个并发连接
          NoIPLimit image/*  # 对图片不做IP限制
    < /Location >

  < Location /mp3 >  # 所有主机的/mp3目录
    MaxConnPerIP 1         # 每IP只允许一个连接请求    
    OnlyIPLimit audio/mpeg video    # 该限制只对视频和音频格式的文件
    < /Location >
< /IfModule >

  

或者虚拟主机的:
< VirtualHost xx.xxx.xx.xx > ##ip 地址
    ServerAdmin easy@phpv.net
    DocumentRoot /home/easy
    ServerName www.phpv.net
  < IfModule mod_limitipconn.c >
      < Location / >    
      MaxConnPerIP 5        
          NoIPLimit image/*      
      < /Location >
      < Location /mp3 >    # 所有主机的/mp3目录
      MaxConnPerIP 2         # 每IP只允许一个连接请求    
      OnlyIPLimit audio/mpeg video # 该限制只对视频和音频格式的文件
      < /Location >
  < /IfModule >
  < /VirtualHost >
 
———————————————————————————————-

限制带宽:

下载模块 ftp://ftp.cohprog.com/pub/apache/module/1.3.0/mod_bandwidth.c
安装:
/usr/local/apache/bin/apxs -c ./mod_bandwidth.c -o /usr/local/apache/libexec/mod_bandwidth.so  
 

<——-以上/usr/local/apache请设置为你的路径

编辑httpd.conf
添加:
 LoadModule bandwidth_module libexec/mod_bandwidth.so
AddModule mod_bandwidth.c
重启你的apache
———————————————————————————————-

给大家推荐两个Apache模块,一个是mod_limitipconn,用来控制Apache的并发联接数,通过该模块可以限制同一来源IP的并发联接数。另一个模块是bw_mod,用于Apache网站带宽控制,可以根据来源IP,网段来划分带宽,也可以根据网站文件类型来限制带宽,参数比较灵活,可以根据自己实际情况进行调整。
mod_limitipconn官方网址为:http://dominia.org/djao/limitipconn.html
mod_mod官方网址为:http://ivn.cl/apache/
具体安装及配置过程就不介绍了,可以参见官方使用说明,这里只简单地谈谈使用心得。
一、对于mod_limitipconn,其实该模块不仅提供客户端并发联接数的控制能力,从安全角度来说还可以起到对抗固定来源IP地址发起的 DOS攻击,包括来源固定的大量访问请求型攻击(大量GET或POST请求型的攻击),当同一来源IP地址的联接数超过限定的值后,会弹回对方的访问请求,给对方一个“503服务临时无效”的响应。当Apache服务器受到大量的访问请求型攻击的时候,由于大量的Apache进程及PHP和MYSQL运行消耗,会导致服务器资源迅速耗尽,网站打开缓慢或瘫痪。如果是此种类型的攻击,使用mod_limitipconn模块则可以有效地提升服务器的抗攻击能力,因为大量的请求被弹回,节省了服务器运行PHP及MYSQL的性能消耗。当然只要请求进了80端口,不管是接受还是弹回请求,Aapche都有运行成本,所以此方法只能是减轻而无法解决,毕竟应用层的处理效率是比较低的。
二、对于网站访问量比较大、使用了mod_limitipconn模块且限制同一客户端并发联接数低于3的情况下,如果用Apache默认的配置参数,极可能经常出现“服务临时无效”的提示。因为Apache默认是设置“KeepAlive on”,且“KeepAliveTimeout 180”,所以一旦建立联接,那么在3分钟内这个联接是不会被释放的。所以如果网站不同页面点击频率比较高或图片资源比较多的话,会经常出现服务临时无效的提示。那么有两种方式去解决,一是加大并发联接数的量,比如设置为普通站点10个并发联接数,图片站点则20个。另一种方式就是如果你不想加大这个值的话,可以设置KeepAlive为off,然后缩短Timeout时间,这样联接会很快被释放出来。具体情况根据需要去调整测试,以得到一个最适合自己站点情况的值。
三、如果要同时限制并发联接数与带宽的话,就用bw_mod+mod_limitipconn,因为虽然bw_mod也可以控制并发联接数,但他是针对某个目录或整个网站的并发联接数,是用来控制服务器端的总联接数,比如设置MaxConnection all 1000,那么这个网站所能接受的最大并发联接数为1000,而并不是限制每一客户端的并发联接数,而mod_limitipconn则是针对同一来源 IP的客户端的并发联接数,所以这两者的联接数限制是有所区别的。
四、个人感觉用了bw_mod及mod_limitipconn模块后,网站访问速度有所下降,能凭直观地感觉出来,并且CPU的负载有所上升。特别是在网站访问量比较大的情况下,这两个模块会消耗一定的主机性能,所以轻重权衡这个得大家自己根据情况来采用了。另外bw_mod里有个参数是用来设置控制精度与频率的,默认是1000毫秒,如果你想提高带宽控制精度就改小这个数值,但会消耗更多的CPU资源,反之亦然,降低精度可提升性能。

首先,download the file mysql-max-5.1.3-alpha-pc-linux-gnu-i686.tar.gz

A. Storage and SQL Node Installation

1.

groupadd mysql
useradd -g mysql mysql

2.

cd /var/tmp       (假设download到此目录)
tar -xzvf -C /usr/local/bin mysql-max-5.1.3-alpha-pc-linux-gnu-i686.tar.gz
ln -s /usr/local/bin/mysql-max-5.1.3-alpha-pc-linux-gnu-i686 mysql

3.

cd mysql
scripts/mysql_install_db –user=mysql

4.

chown -R root .
chown -R mysql data
chgrp -R mysql .

每个data node上的数据目录是/usr/local/mysql/data.在我们配置management node的时候,可以利用这个信息.

5.

cp support-files/mysql.server /etc/rc.d/init.d/
chmod +x /etc/rc.d/init.d/mysql.server
chkconfig –add mysql.server

B. Management Node Installation

(management) node上无须安装 mysqld executable,  只需安装downloaded -max archive中的MGM server and client就可以.
以下步骤在Cluster management node host上安装ndb_mgmd和ndb_mgm:

1. 

进入/var/tmp(假设download至此目录), 从文件中解开ndb_mgm和ndb_mgmd至一个合适的目录,例如/usr/local/bin;
cd /var/tmp
tar -zxvf mysql-max-5.1.3-alpha-pc-linux-gnu-i686.tar.gz /usr/local/bin ‘*/bin/

2.

进入刚才你解压的目录,并使该目录中的文件为可执行:
cd /usr/local/bin
chmod +x ndb_mgm*

安装完毕!