mysql计数器表的设计

问题:如果使用数据库表保存计数器,则在更新计数器时可能会碰到并发问题。

  • 假设拥有一个计数器表,只有一行数据来记录网站的点击次数:
    create table hit_counter (
    cnt int unsigned not null
    ) engine = InnoDB;
    
  • 每当需要增加次数时都需要进行更新:
    update hit_counter 
    set cnt = cnt + 1;
    
  • 问题在于,每当增加一个计数,那么这条记录都会有一个全局互斥锁,所有需要修改次数的事务只能串行执行,非常影响效率。想要获得更高的并发更新性能,可以计数器保存多行,每次随机选择一行进行更新,需要对表进行如下修改:
    create table hit_counter(
    slot tinyint unsigned not null primary key,
    cnt int unsigned not null
    ) engine = InnoDB; ```
    
  • 假设在表中增加100行记录,现在选择一个随机的槽(slot)进行更新:
    update hit_counter
    set cnt = cnt + 1
    where slot = rand() * 100;
    
  • 需要查询统计结果时,只需要进行聚合查询:
    select sum(cnt)
    from hit_counter;
    
  • 如果需求是每隔一个时间开始一个新的计数器,假如每天一个,那么就再对表进行如下修改:
    create table daily_hit_counter (
    day date not null,
    solt tinyint unsigned not null,
    cnt int unsigned not null,
    primary key(day, slot)
    ) engine = InnoDB;
    
  • 该需求,就不用提前预生成100行记录,而是使用on duplicate key update 来代替:
    insert into daily_hit_counter
    values (current_date, rand() * 100, 1)
    on duplicate key update cnt = cnt + 1;
    
  • 避免表变得太大,可以写一个周期性任务,合并每天所有的表都0号slot,并删除其他slot的行。
原文地址:https://www.cnblogs.com/dwtfukgv/p/14678654.html