1

业务缓存之可行性?

 2 years ago
source link: https://forrestsu.github.io/posts/architecture/cache/caching-feasibility/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

业务缓存之可行性?

2021年1月8日
| 字数 1888
| 阅读 23

1 Preface

在业务系统中,为了提高服务的性能,降低平均时延,一个常用的手段:增加cache。

鲁迅:-)人们发明一种方法解决一个问题,而几乎总是会引入另一个问题。

那么可能会问:Cache 要加在哪里,要缓存多久,才会更有效? 下面就拿一个例子,来展开看看。

一般而言,需要对执行频率高,耗时占比大的逻辑,优先增加Cache。 但是要注意:增加 Cache 不能影响到业务的正确性。

适用场景:数据变化不频繁,因为一旦数据发生变化,Cache可能产生不一致。 对于不一致,还需要设计一个合理的失效时间,在业务可接受的误差之内增加cache。

3 实际场景分析

现在有个下游的缓存服务,请求量占Top1,如果仍然引入分布式缓存(如redis, memcached意义不大), 那么我们考虑增加 memory cache,在加Cache 之前,我们要对key的重复率进行分析。分析流程如下:

数据获取 → 解析数据 → 分析数据 → 可视化

3.1 数据获取

如果有数据分析平台,通过定制 sql 分析即可。 由于服务对于还未上报数据分析平台,所以尝试使用tcpdump,抓取连续10分钟的业务包来分析:

sudo timeout 10m  tcpdump -i eth1 dst port 13196 -w out.cap  -v
# capture need sudo

我们这里只捕获请求包 dst port 13196

3.2 解析数据

借助之前我们实现的 wireshark 协议插件, 略微改造一下: 在解析协议包时,把想要的字段 dump 一份,用于离线分析。

time tshark -r ad_packet_13196_10m.cap  >/dev/null
# 2m05.50s real		60.79s user		61.89s sys

经过 2 分钟的解析,我们拿到了 vid.txt 列表(95w条记录), 看下数据样例(head -n5):

a320677esiq
j002624fcc5
d31318c4461
s0034ii0vrd
b0030omcpkx
...

3.3 分析数据 (重复单词个数统计)

借助 unique, sort 强有力的命令行工具:

cat vid.txt | sort | uniq -c | sort -k1nr > rank_10m.txt

解释一下:sort -k1 表示按第1列排序,n 按数值比较,r 逆序

处理完之后(25w条记录)。 看下数据样例(head -n5):

10242 t0035sxfrtv
8098  o3164lnasuz
6294  x00358r6ch4
...
1     z3206ww0zix
1     z3206z5mfq5

3.4 使用 awk 进行数据区分统计

#!/bin/awk -f

#运行前
BEGIN {
    less2 = 0
    less20 = 0
    less50 = 0
    moreThan50 = 0
    total = 0
    printf "NAME   \t less2 \tless20 \tless50 \t moreThan50\n"
    printf "-----+------+-----+------+-----+------+\n"
}
#运行中
{
    total += $1
    if ($1 < 2) {
        less2+=$1
    } else if ($1 < 20) {
        less20+=$1
    } else if ($1 < 50) {
        less50+=$1
    } else {
        moreThan50+=$1
    }
}
#运行后
END {
    printf "TOTAL: %d \n", total
    printf " buckets: \t%d \t%d \t%d \t%d \n", less2, less20, less50, moreThan50
    total = total/100.0
    printf " Percent: \t%2.2f%% \t%2.2f%% \t%2.2f%% \t%2.2f%% \n",
    less2/total, less20/total, less50/total, moreThan50/total
}
$ awk -f count.awk rank_10m.txt
NAME   	 less2 	less20 	less50 	 moreThan50
-----+------+-----+------+-----+------+
TOTAL: 948317
 buckets: 	155348 	399847 	108937 	284185
 Percent: 	16.38% 	42.16% 	11.49% 	29.97%

可视化展示:

借助于 Linux 的小工具,实现数据批处理、分析,非常高效而且实用。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK