转载请注明出处哈:http://carlosfu.iteye.com/blog/2269678
一、引出热点key问题
我们通常使用 缓存 + 过期时间的策略来帮助我们加速接口的访问速度,减少了后端负载,同时保证功能的更新,一般情况下这种模式已经基本满足要求了。
但是有两个问题如果同时出现,可能就会对系统造成致命的危害:
(1) 这个key是一个热点key(例如一个重要的新闻,一个热门的八卦新闻等等),所以这种key访问量可能非常大。
(2) 缓存的构建是需要一定时间的。(可能是一个复杂计算,例如复杂的sql、多次IO、多个依赖(各种接口)等等)
于是就会出现一个致命问题:在缓存失效的瞬间,有大量线程来构建缓存(见下图),造成后端负载加大,甚至可能会让系统崩溃 。
二、四种解决方案(注释:第1,2种方法来自Tim Yang博客)
我们的目标是:尽量少的线程构建缓存(甚至是一个) + 数据一致性 + 较少的潜在危险,下面会介绍四种方法来解决这个问题:
1. 使用互斥锁(mutex key): 这种解决方案思路比较简单,就是只让一个线程构建缓存,其他线程等待构建缓存的线程执行完,重新从缓存获取数据就可以了(如下图)
如果是单机,可以用synchronized或者lock来处理,如果是分布式环境可以用分布式锁就可以了(分布式锁,可以用memcache的add, redis的setnx, zookeeper的添加节点操作)。
下面是Tim yang博客的代码,是memcache的伪代码实现
- if (memcache.get(key) == null) {
- // 3 min timeout to avoid mutex holder crash
- if (memcache.add(key_mutex, 3 * 60 * 1000) == true) {
- value = db.get(key);
- memcache.set(key, value);
- memcache.delete(key_mutex);
- } else {
- sleep(50);
- retry();
- }
- }
如果换成redis,就是:
- String get(String key) {
- String value = redis.get(key);
- if (value == null) {
- if (redis.setnx(key_mutex, "1")) {
- // 3 min timeout to avoid mutex holder crash
- redis.expire(key_mutex, 3 * 60)
- value = db.get(key);
- redis.set(key, value);
- redis.delete(key_mutex);
- } else {
- //其他线程休息50毫秒后重试
- Thread.sleep(50);
- get(key);
- }
- }
- }
2. "提前"使用互斥锁(mutex key):
在value内部设置1个超时值(timeout1), timeout1比实际的memcache timeout(timeout2)小。当从cache读取到timeout1发现它已经过期时候,马上延长timeout1并重新设置到cache。然后再从数据库加载数据并设置到cache中。伪代码如下:
- v = memcache.get(key);
- if (v == null) {
- if (memcache.add(key_mutex, 3 * 60 * 1000) == true) {
- value = db.get(key);
- memcache.set(key, value);
- memcache.delete(key_mutex);
- } else {
- sleep(50);
- retry();
- }
- } else {
- if (v.timeout <= now()) {
- if (memcache.add(key_mutex, 3 * 60 * 1000) == true) {
- // extend the timeout for other threads
- v.timeout += 3 * 60 * 1000;
- memcache.set(key, v, KEY_TIMEOUT * 2);
- // load the latest value from db
- v = db.get(key);
- v.timeout = KEY_TIMEOUT;
- memcache.set(key, value, KEY_TIMEOUT * 2);
- memcache.delete(key_mutex);
- } else {
- sleep(50);
- retry();
- }
- }
- }
3. "永远不过期":
这里的“永远不过期”包含两层意思:
(1) 从redis上看,确实没有设置过期时间,这就保证了,不会出现热点key过期问题,也就是“物理”不过期。
(2) 从功能上看,如果不过期,那不就成静态的了吗?所以我们把过期时间存在key对应的value里,如果发现要过期了,通过一个后台的异步线程进行缓存的构建,也就是“逻辑”过期
从实战看,这种方法对于性能非常友好,唯一不足的就是构建缓存时候,其余线程(非构建缓存的线程)可能访问的是老数据,但是对于一般的互联网功能来说这个还是可以忍受。
- String get(final String key) {
- V v = redis.get(key);
- String value = v.getValue();
- long timeout = v.getTimeout();
- if (v.timeout <= System.currentTimeMillis()) {
- // 异步更新后台异常执行
- threadPool.execute(new Runnable() {
- public void run() {
- String keyMutex = "mutex:" + key;
- if (redis.setnx(keyMutex, "1")) {
- // 3 min timeout to avoid mutex holder crash
- redis.expire(keyMutex, 3 * 60);
- String dbValue = db.get(key);
- redis.set(key, dbValue);
- redis.delete(keyMutex);
- }
- }
- });
- }
- return value;
- }
4. 资源保护:
之前在缓存雪崩那篇文章提到了netflix的hystrix,可以做资源的隔离保护主线程池,如果把这个应用到缓存的构建也未尝不可。
三、四种方案对比:
作为一个并发量较大的互联网应用,我们的目标有3个:
1. 加快用户访问速度,提高用户体验。
2. 降低后端负载,保证系统平稳。
3. 保证数据“尽可能”及时更新(要不要完全一致,取决于业务,而不是技术。)
所以第二节中提到的四种方法,可以做如下比较,还是那就话:没有最好,只有最合适。
解决方案 | 优点 | 缺点 |
简单分布式锁(Tim yang) |
1. 思路简单 2. 保证一致性 |
1. 代码复杂度增大 2. 存在死锁的风险 3. 存在线程池阻塞的风险 |
加另外一个过期时间(Tim yang) | 1. 保证一致性 | 同上 |
不过期(本文) |
1. 异步构建缓存,不会阻塞线程池 |
1. 不保证一致性。 2. 代码复杂度增大(每个value都要维护一个timekey)。 3. 占用一定的内存空间(每个value都要维护一个timekey)。 |
资源隔离组件hystrix(本文) |
1. hystrix技术成熟,有效保证后端。 2. hystrix监控强大。
|
1. 部分访问存在降级策略。 |
四、总结
1. 热点key + 过期时间 + 复杂的构建缓存过程 => mutex key问题
2. 构建缓存一个线程做就可以了。
3. 四种解决方案:没有最佳只有最合适。
五、参考文献:(本文部分代码和图来自如下两篇博客)
相关推荐
分布式Mutex 使用Redis的简单分布式锁。 安装(尚未上传到rubygems) gem install distributed_mutex 或者,如果您正在使用Rails,则可以通过Bundler安装。将此行添加到您的应用程序的Gemfile中: gem '...
npm install level-mutex-batch 用法 var lmbatch = require ( 'level-mutex-batch' ) var batch = lmbatch ( db ) // db is a levelup batch ( [ { type : 'put' , key : 'hello' , value : 'world-1' } ] , ...
8 aos_task_key_create 9 aos_task_key_delete 10 aos_task_setspecific 11 aos_task_getspecific 12 aos_mutex_new 13 aos_mutex_free 14 aos_mutex_lock 15 aos_mutex_unlock 16 aos_mutex_is_valid 17 ...
任务AppTaskKeyScan每50ms扫描KEY2状态,若KEY2按键按下, 则释放信号量激活任务AppTaskSem,使LED2状态反转 3、Mbox 为UCOS II邮箱的使用提供一个参考 任务AppTaskKeyScan每50ms扫描KEY2状态,若KEY2按键按下...
名称KeyedMutex::Memcached - 使用 ...until ( my $value = $cache->get($key) ) { { if ( my $lock = $mutex->lock( $key, 1 ) ) { #locked read from DB $value = get_from_db($key); $cache->set($key, $valu
You will learn the key differences between classical polymorphism and generic programming, the foundation of the STL. You will also learn how to use the various algorithms and containers in the STL ...
printf("the key word of the thread is : %d\n the name of thread is : %s\n the state of the thread is ",i,tcb[i].name); switch(tcb[i].state) { case (1): printf("Running \n");break; case (2)...
small library for c, includes array, map, string, obj, value, thread, mutex, file, event emitter... C语言是我最常用的编程语言之一,不过对它也算是爱恨交加了,喜欢它的简洁和高效,但是经常需要重复造轮子...
创建互斥锁: mutex:mutex name 以 # 开头的行作为注释被忽略 示例配置文件: 一个包含内容的文件 file:C:\Users\User\Documents\test.txt=这是文件的内容 一个文件,没有内容 文件:C:\Users\User\Documents\test...
resource = " example_key: #{ user_id } " lock_exp_sec = 10 case Redlock . lock (resource, lock_exp_sec) do { :ok , mutex} -> # some other code which write and read on RDBMS, KVS or other storage # ...
编辑文件的 Listen 80 为其他可用的端口,例如 Listen 81,然后重新启动 - 这样就不会那个问题了。 3. 现在可以测试 Apache 服务器是否正确运行,将浏览器指向 http://localhost/ - 将会看到一个预先配置的网站...
mutex_lock(&probe_hdl_lock); vfe_print("probe_work_handle start!\n"); vfe_dbg(0,"v4l2_device_register\n"); #ifdef USE_SPECIFIC_CCI vfe_clk_open(dev); #endif /* v4l2 device register */ ret = v4l2...
mutex_lock(&probe_hdl_lock); vfe_print("probe_work_handle start!\n"); vfe_dbg(0,"v4l2_device_register\n"); #ifdef USE_SPECIFIC_CCI vfe_clk_open(dev); #endif /* v4l2 device register */ ret = v4l2...
OpenSemaphore PulseEvent ReleaseMutex ReleaseSemaphore ResetEvent ResumeThread SetEvent SetPriorityClass SetThreadPriority Sleep SuspendThread TerminateProcess ...
使用(key:int)->(value:void *)的简单HashTable实现。 散列“函数”是一个简单的模(键%hashTableSize)。 客户端-服务器逻辑: 服务器分配大小为“ OPS”(在Utils.h中定义)+ sizeof(int)+ sizeof...
2、(可选修改/根据和全志R16平台的tina v1.0的系统下的SDK对照发现的问题。全志R16的最新的tina v2.1大幅度修改cameratest的源代码了!) W:\ov5640_spi20_r40t\package\allwinner\cameratest\src\common\hawkview....
printf("Press any key to quit!\n"); _getch(); return 0; } //确认是否还有对同一产品的消费请求未执行; bool IfInOtherRequest(int req) { for(int i=0;i;i++) for(int j=0;j[i].n_request;j++) if...
// Change the registry key under which our settings are stored. // TODO: You should modify this string to be something appropriate // such as the name of your company or organization. ...
8.下面的代码有什么问题?并请给出正确的写法。 void DoSomeThing(char* p) { char str[16]; int n; assert(NULL != p); sscanf(p, "%s%d", str, n); if (0 == strcmp(str, "something")) { ... } } A: ...
注册机制作示例 \KeyFile...................KeyFile保护方式 ├──Check..............KeyFile保护示例 └──KeyGen.............注册机制作示例 \CallDllCheck..............用DLL实现注册认证 └──CallCheck....