0

缓存模式概要 - 指尖挥舞

 1 year ago
source link: https://www.cnblogs.com/naiyou/p/16331256.html
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.

在大部分C端项目中,如果想提升系统并发能力,需要上缓存。但是缓存的实现方式多种多样,本文主要穿透实现,直接阐述设计模式上的概念,方便各种实现对号入座。

  • SoR(System-of-Record )
    记录系统,这里指的就是实际数据存放的系统,一般指业务对应的数据库

1. Cache-aside

616195-20220531171904605-671508807.png
  • 读取伪代码

    点击查看代码
    v = cache.get(k)
    if (v == null) {
      v = sor.get(k)
      cache.put(k, v)
    }
    
  • 写入伪代码

    点击查看代码
    v = newV
    sor.put(k, v)
    cache.put(k, v)
    

这种模式下,需要应用程序嵌入缓存处理的逻辑:
- 在查询时,判断缓存是否存在记录,有直接返回;没有则从SoR中获取,再更新缓存。
- 在写入时,缓存必须和记录系统一起更新

2. Cache-as-SoR

缓存即 SoR 模式: 使用缓存和使用记录系统无差别(无感知)。这种模式下对读写场景需要做具体实现:

2.1 读场景

  • Read-through
    读场景下,一般采用Read-through模式,缓存中间件提供一个loader组件,对应用程序来说只与loader交互,实际底层并不关心实现。

2.2 写场景

写场景下,主要描述如何更新缓存,有以下两种选择

  • Write-through
    更新数据时,缓存中间件提供一个write组件,对应用程序来说只需要知道更新了数据。具体逻辑由组件实现,去更新记录系统,并更新缓存
  • Write-behind
    在更新数据的时候,只更新缓存,不更新数据库,从而提高数据更新的响应速度。缓存会异步地批量更新数据库,代价就是数据不是强一致的。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK