mysql实现高并发计数器

mysql实现高并发计数器

 

因为在高并发下 set aa=aa+1要进行锁表 不然会计算错误 但是锁表了 性能就降低了 所以 计数器采用另外一种方案

CREATE TABLE `article_view`(
`article_id` int(11) NOT NULL,
`pond` tinyint(4) NOT NULL COMMENT '池子,就是用来随机用的',
`view` int(11) NOT NULL,
PRIMARY KEY (`article_id`,`pond`)
)ENGINE=InnoDB;
  INSERT INTO `article_view` (`article_id`, `pond`, `view`) VALUES (123, RAND()*100, 1) ON DUPLICATE KEY UPDATE `view`=`view`+1

 

SELECT SUM(`view`) FROM `article_view` WHERE `article_id`=123

 查询出来的数据再更新到字段

如果希望减少表的行数,以避免表变得太大,可以写一个周期执行的任务,合并所有结果到0 号槽,并且删除所有其他的槽:
UPDATE daily_hit_counter as c
INNER JOIN (
SELECT day, SUM(cnt) AS cnt, MIN(slot) AS mslot
FROM daily_hit_counter
GROUP BY day
) AS x USING(day)
SET c.cnt = IF(c.slot = x.mslot, x.cnt, 0),
c.slot = IF(c.slot = x.mslot, 0, c.slot);

DELETE FROM daily_hit_counter WHERE slot <> 0 AND cnt = 0;

 

posted @ 2020-11-03 09:03  newmiracle宇宙  阅读(696)  评论(0编辑  收藏  举报