create table kp_hit_counter ( cnt int unsigned not null) engine=innodb;create table kp_hit_counter2 ( id int unsigned not null primary key, cnt int unsigned not null) engine=innodb;创建表工具:http_load1000次请求,并发:1041 fetches, 1020 max parallel, bytes, in 10.0008 seconds# 一共请求连接41次,最大并发线程1020个,持续10.0008秒内,总传输速率为 bytes 20778 mean bytes/connection#每次请求连接平均数据量(÷41)4.09969 fetches/sec, 85183.3 bytes/sec#每秒的响应请求连接数为4.09969个,每秒传输的数据为85183.3btyes/毫秒msecs/connect: 264.607 mean, 269.482 max, 262.187 min#每次连接平均响应时间:264.607毫秒,最大时间:269.482毫秒,最小时间:262.187毫秒msecs/first-response: 1949.27 mean, 5394.21 max, 380.501 min#每次连接平均返回时间:1949.27毫秒,最大时间:5394.21毫秒,最小时间:380.501毫秒HTTP response codes:
code 200 -- 41#HTTP返回码:200 ,一共41次。模拟环境第一种方案:update kp_hit_counter set cnt = cnt+1;第一种结果:
第二种方案:
建立多行,随机计数后求和,提高并发处理能力:
update kp_hit_counter2 set cnt = cnt+1 where id = RAND() * 100这是原书作者给出的例子,并没任何作用
这是网上查的取随机数改的
update kp_hit_counter2 set cnt = cnt+1 where id = round(RAND() * 100);
以上写法有坑,你会发现计数会小于1000,甚至是1000,还好我测试了。
rand是0-1的浮点数,以上写法可能出现0,导致计数失败,后来又改良成以下还是不行:
update kp_hit_counter2 set cnt = cnt+1 where id = (round(RAND() * 99)+1); 所以取随机数我交给PHP去做再也没出现计数错误了,本身也应该这么做: