【Redis多级缓存】安装OpenResty

1.安装

首先你的Linux虚拟机必须联网

1)安装开发库

首先要安装OpenResty的依赖开发库,执行命令:

yum install -y pcre-devel openssl-devel gcc --skip-broken

2)安装OpenResty仓库

你可以在你的 CentOS 系统中添加 openresty 仓库,这样就可以便于未来安装或更新我们的软件包(通过 yum check-update 命令)。运行下面的命令就可以添加我们的仓库:

yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo

如果提示说命令不存在,则运行:

yum install -y yum-utils 

然后再重复上面的命令

3)安装OpenResty

然后就可以像下面这样安装软件包,比如 openresty

yum install -y openresty

4)安装opm工具

opm是OpenResty的一个管理工具,可以帮助我们安装一个第三方的Lua模块。

如果你想安装命令行工具 opm,那么可以像下面这样安装 openresty-opm 包:

yum install -y openresty-opm

5)目录结构

默认情况下,OpenResty安装的目录是:/usr/local/openresty

在这里插入图片描述

看到里面的nginx目录了吗,OpenResty就是在Nginx基础上集成了一些Lua模块。

6)配置nginx的环境变量

打开配置文件:

vi /etc/profile

在最下面加入两行:

export NGINX_HOME=/usr/local/openresty/nginx
export PATH=${NGINX_HOME}/sbin:$PATH

NGINX_HOME:后面是OpenResty安装目录下的nginx的目录

然后让配置生效:

source /etc/profile

2.启动和运行

OpenResty底层是基于Nginx的,查看OpenResty目录的nginx目录,结构与windows中安装的nginx基本一致:

在这里插入图片描述

所以运行方式与nginx基本一致:

# 启动nginx
nginx
# 重新加载配置
nginx -s reload
# 停止
nginx -s stop

nginx的默认配置文件注释太多,影响后续我们的编辑,这里将nginx.conf中的注释部分删除,保留有效部分。

修改/usr/local/openresty/nginx/conf/nginx.conf文件,内容如下:


#user  nobody;
worker_processes  1;
error_log  logs/error.log;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       8081;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

在Linux的控制台输入命令以启动nginx:

nginx

然后访问页面:http://192.168.67.233:8081,注意ip地址替换为你自己的虚拟机IP:

3.备注

加载OpenResty的lua模块:

#lua 模块
lua_package_path "/usr/local/openresty/lualib/?.lua;;";
#c模块     
lua_package_cpath "/usr/local/openresty/lualib/?.so;;";  

common.lua

-- 封装函数,发送http请求,并解析响应
local function read_http(path, params)
    local resp = ngx.location.capture(path,{
        method = ngx.HTTP_GET,
        args = params,
    })
    if not resp then
        -- 记录错误信息,返回404
        ngx.log(ngx.ERR, "http not found, path: ", path , ", args: ", args)
        ngx.exit(404)
    end
    return resp.body
end
-- 将方法导出
local _M = {  
    read_http = read_http
}  
return _M

释放Redis连接API:

-- 关闭redis连接的工具方法,其实是放入连接池
local function close_redis(red)
    local pool_max_idle_time = 10000 -- 连接的空闲时间,单位是毫秒
    local pool_size = 100 --连接池大小
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
    if not ok then
        ngx.log(ngx.ERR, "放入redis连接池失败: ", err)
    end
end

读取Redis数据的API:

-- 查询redis的方法 ip和port是redis地址,key是查询的key
local function read_redis(ip, port, key)
    -- 获取一个连接
    local ok, err = red:connect(ip, port)
    if not ok then
        ngx.log(ngx.ERR, "连接redis失败 : ", err)
        return nil
    end
    -- 查询redis
    local resp, err = red:get(key)
    -- 查询失败处理
    if not resp then
        ngx.log(ngx.ERR, "查询Redis失败: ", err, ", key = " , key)
    end
    --得到的数据为空处理
    if resp == ngx.null then
        resp = nil
        ngx.log(ngx.ERR, "查询Redis数据为空, key = ", key)
    end
    close_redis(red)
    return resp
end

开启共享词典:

# 共享字典,也就是本地缓存,名称叫做:item_cache,大小150m
lua_shared_dict item_cache 150m; 
### 使用OpenResty实现多级缓存 #### 方法概述 为了提高系统的响应速度并减轻后端服务器的压力,在请求到达最终的服务提供者之前,可以设置多个层次的缓存机制。当请求进入OpenResty之后,会先尝试访问位于内存中的快速缓存层——例如Redis[^3]。 如果在这一层未能找到所需的数据,则继续向更深层级去获取数据直至原始数据源(如Tomcat应用服务器),并将新获得的结果逐层回填至各级缓存中以便后续相同请求可以直接命中最近的一级缓存而无需再次穿透到下一层甚至直达数据库等底层存储单元。 #### 实现方案 以下是基于Lua脚本的一个简单示例来展示如何利用OpenResty配合Redis构建一个多级缓存体系: ```lua -- 加载必要的库 local redis = require "resty.redis" -- 创建一个新的 Redis 连接实例 local red = redis:new() -- 设置超时时间 (可选) red:set_timeout(1000) -- 1秒 -- 尝试连接到 Redis 服务器 local ok, err = red:connect("127.0.0.1", 6379) if not ok then ngx.say("failed to connect: ", err) return end -- 获取 URL 参数作为 key local args = ngx.req.get_uri_args() local cache_key = args["key"] -- 查询 Redis 缓存 local res, err = red:get(cache_key) if type(res) ~= 'nil' and res ~= ngx.null then -- 如果存在则直接返回缓存内容 ngx.say("hit redis cache:", res) else -- 若不存在于 Redis 中,则查询 Tomcat 并更新缓存 -- 假设这里调用了某个接口从 tomcat 获取数据... local data_from_tomcat = get_data_from_tomcat() -- 向 Redis 添加新的条目 local ttl = 60 * 5 -- 设置过期时间为五分钟 local ok, err = red:setex(cache_key, ttl, data_from_tomcat) if not ok then ngx.log(ngx.ERR, "Failed setting value into redis: ", err) end -- 返回给客户端 ngx.say(data_from_tomcat) end -- 断开与 Redis 的连接 local ok, err = red:close() if not ok then ngx.say("failed to close: ", err) return end ``` 此段代码展示了如何在一个HTTP请求到来时,首先检查是否存在对应的缓存记录;如果有,则立即返回该记录的内容而不必进一步处理;如果没有匹配项,则转而去询问实际的应用程序(Tomcat),取得最新版本的信息后再将其写回到Redis里供将来使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KiriSoyer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值