跳至主要內容

多级缓存

知识库实战项目高可用高并发架构高可用高并发架构大约 2 分钟

在系统架构中应该使用那些缓存

  1. 浏览器缓存
  2. CDN 缓存(静态资源:js,css,视频,文件)
  3. 接入层 nginx/openresty 缓存
  4. 堆内存缓存(jvm 进程级别的缓存)
  5. 分布式缓存(redis,memcached)
  6. 数据库缓存(压力非常小)

本地缓存

  • 你愿意消耗一些内存空间来提升速度。
  • 预料到某些键会被查询一次以上。
  • 缓存中存放的数据总量不会超出内存容量。
@configuration
public class GuavaCacheConfig{
    private Cache<String,Object> commonCache = null;
    @PostConstruct
    public void init(){
        commonCache = CacheBuilder.newBuilder()
            .initialCapacity(10)
            .maximunSize(100)
            // 设置缓存写入后的过期时间
            .expireAfterWrite(60,TimeUnit.SECONDS)
            .build()
    }
    @Bean
    public Cache<String,Object> getCommonCache(){
        return commonCache;
    }
}

Redis 缓存

Openresty 内存字典缓存

  1. openresty 接入 lua 脚本
    lua 接入指令:https://www.nginx.com/resources/wiki/modules/lua/#directivesopen in new window
# 安装openresty:
wget https://openresty.org/download/openresty-1.19.3.1.tar.gz
tar -zxvf
./configure
# 默认被安装到/usr/local/openresty
make && make install

# content_by_lua 接入lua脚本
location /lua1 {
    default_type text/html;
    content_by_lua 'ngx.say("hello lua!!")';
}
# content_by_lua_file 通过文件的方式引入lua脚本
location /lua2 {
    default_type text/html;
    content_by_lua_file lua/test.lua; #  test.java ,test.py
}
# test.lua
local args = ngx.req.get_uri_args()  # 获取参数对象
ngx.say("hello openresty! lua is so easy!==="..args.id)  # 获取参数值,组装值:..
# 转发请求
location /lua3 {
    content_by_lua_file lua/details.lua;
}
# details.lua
ngx.exec('/seckill/goods/detail/1'); # 转发请求

  1. Openresty 内存字典缓存
# 在openresty服务器开辟一块128m空间存储缓存数据
lua_shared_dict ngx_cache 128m;
-- 基于内存字典实现缓存
-- 添加缓存实现
function set_to_cache(key,value,expritime)
    -- 判断时间是否存在
    if not expritime then
        expritime = 0
    end
    -- 获取本地内存字典对象
    local ngx_cache = ngx.shared.ngx_cache

    -- 向本地内存字典添加缓存数据
    local succ,err,forcibel = ngx_cache:set(key,vlaue,expritime)
    return succ
end
-- 获取缓存实现
function get_from_cache(key)
    -- 获取本地内存字典对象
    local ngx_cache = ngx.shared.ngx_cache
    -- 从本地内存字典中获取数据
    local value = ngx_cache:get(key)
    return value
end
-- 利用lua脚本实现一些简单业务
-- 获取请求参数对象
local params = ngx.req.get_uri_args()
-- 获取参数
local id = params.id
-- 先从内存字典获取缓存数据
local goods = get_from_cache("seckill_goods_"..id)
-- 如果内存字典中没有缓存数据
if goods == nil then
    -- 从后端服务(缓存,数据库)查询数据,完毕在放入内存字典缓存即可
    local  res = ngx.location.capture("/seckill/goods/detail/"..id)
    -- 获取查询结果
    goods = res.body
    -- 向本地内存字典添加缓存数据
    set_to_cache("seckill_goods_"..id,goods,60)
end
-- 返回结果
ngx.say(goods)

Openresty Lua+redis

-- 引入redis库
local redis = require "resty.redis"
-- 调用方法,获取redis对象
local red = redis:new();