OpenResty 最佳实践学习–实战演习笔记(4)

本篇简单记录openresty连接redis数据库和缓存的一些东西,也基本上是官网上的一些例子和知识,作为整理方便自己后续回顾!openresty连接redis因为我本地服务器安装了redis,这里只简单记录连接redis的过程!1.启动redis服务[root@localhost ~]# /usr/local/bin/redis-server /root/dufy/redis/redis-3.0.

大家好,又见面了,我是全栈君。

本篇简单记录openresty连接redis数据库和缓存的一些东西,也基本上是官网上的一些例子和知识,作为整理方便自己后续回顾!

openresty连接redis

因为我本地服务器安装了redis,这里只简单记录连接redis的过程!

1.启动redis服务

[root@localhost ~]# /usr/local/bin/redis-server /root/dufy/redis/redis-3.0.4/redis.conf
[root@localhost ~]# 
[root@localhost ~]# ps -ef | grep redis
root      1925     1  0 22:46 ?        00:00:00 /usr/local/bin/redis-server *:6379                                 
root      1929  1915  0 22:46 pts/0    00:00:00 grep redis
[root@localhost ~]# 

[root@localhost ~]# /usr/local/bin/redis-cli -p 6379
127.0.0.1:6379> set hello 123
OK
127.0.0.1:6379> get hello
"123"
127.0.0.1:6379> 

2.openresty中配置连接redis的代码
在 openresty的 /opt/openresty/nginx/conf/ 下面的nginx.conf http-> server中配置,下面的配置在官方文档中:lua-resty-redis Synopsis!

 #测试连接redis
    location /redis {
            content_by_lua_block {
                local redis = require "resty.redis"  #引入redis,相当与java 的import
                local red = redis:new()

                red:set_timeout(1000) -- 1 sec

                -- or connect to a unix domain socket file listened
                -- by a redis server:
                -- local ok, err = red:connect("unix:/path/to/redis.sock")

                local ok, err = red:connect("127.0.0.1", 6379)
                if not ok then
                    ngx.say("failed to connect: ", err)
                    return
                end

                ok, err = red:set("dog", "an animal")
                if not ok then
                    ngx.say("failed to set dog: ", err)
                    return
                end

                ngx.say("set result: ", ok)

                local res, err = red:get("dog")
                if not res then
                    ngx.say("failed to get dog: ", err)
                    return
                end

                if res == ngx.null then
                    ngx.say("dog not found.")
                    return
                end

                ngx.say("dog: ", res)

                red:init_pipeline()
                red:set("cat", "Marry")
                red:set("horse", "Bob")
                red:get("cat")
                red:get("horse")
                local results, err = red:commit_pipeline()
                if not results then
                    ngx.say("failed to commit the pipelined requests: ", err)
                    return
                end

                for i, res in ipairs(results) do
                    if type(res) == "table" then
                        if res[1] == false then
                            ngx.say("failed to run command ", i, ": ", res[2])
                        else
                            -- process the table value
                        end
                    else
                        -- process the scalar value
                    end
                end

                -- put it into the connection pool of size 100,
                -- with 10 seconds max idle time
                local ok, err = red:set_keepalive(10000, 100)
                if not ok then
                    ngx.say("failed to set keepalive: ", err)
                    return
                end

                -- or just close the connection right away:
                -- local ok, err = red:close()
                -- if not ok then
                -- ngx.say("failed to close: ", err)
                -- return
                -- end
            }
        }

3.测试连接
(1)启动openresty

[root@localhost ~]# sudo /opt/openresty/nginx/sbin/nginx -c /opt/openresty/nginx/conf/nginx.conf -p /opt/openresty/nginx/

nginx:  lua_code_cache is off; this will hurt performance in /opt/openresty/nginx/conf/nginx.conf:46
[root@localhost ~]# 
[root@localhost ~]# 
[root@localhost ~]# ps -ef | grep nginx
root      1957     1  0 22:56 ?        00:00:00 nginx: master process /opt/openresty/nginx/sbin/nginx -c /opt/openresty/nginx/conf/nginx.conf -p /opt/openresty/nginx/
nobody    1958  1957  0 22:56 ?        00:00:00 nginx: worker process                                                                           
root      1960  1915  0 22:56 pts/0    00:00:00 grep nginx
[root@localhost ~]# 

(2)测试redis是否ok

[root@localhost ~]# curl http://localhost:8080/redis
set result: OK
dog: an animal
[root@localhost ~]# 

openresty缓存简单介绍

openresty怎么做缓存的?

1.shared_dict 字典缓存

–纯内存,多个Worker之间共享,会有锁的操,保证原子性
–预设 缓存的大小
– API更多一点

(1)修改nginx,conf
lua_shared_dict my_cache 128m;

(2)lua代码中
function get_from_cache(key)
local my_cache = ngx.shared.my_cache
local value = my_cache:get(key)
return value
end

注意:生产环境我们会根据业务功能不的不同,拆分出多个shared_dict!
避免锁的竞争!

2.lua_resty_lrucache

–最近最少使用算法
– 预设 缓存key的个数
– 每个Worker单独占用,减少了锁的竞争,但是增大了内存的占用
–lrucache API 现在特别简单

local lrucache = require "resty.lrucache"
local c = lrucahce.new(200) --allow up to 200 items in the cache

if not c then 
    return error("failed to create the cahce : " .. (err or "unknownb"))
end

c:set("dog",32)
ngx.say("dog :" , c:get("dog"))

3.高性能的缓存服务器,考虑
–缓存 失效风暴(缓存雪崩)
local value = get_from_cache(key)
if not value then
value = query_db(sql)
set_to_cache(value,timeout = 100)
end
return value

lua-resty-lock 官方文档 有详细的介绍!

例子:不用缓存和使用缓存的对比

nginx.conf
(1)

#---
    # lua_code_cache : 默认on 打开,使用缓存,测试时候可以关闭 ,设置off; 压力测试的时候打开,要不很影响性能
    #---
    lua_code_cache on;

(2)

 #测试openresty的缓存
    location /get_value{
        content_by_lua_file learn_lua/cache/get_value.lua;
    }

(3)新建get_value.lua /learn_lua/cache/get_value.lua

local redis = require "resty.redis"
local red = redis:new()

red:set_timeout(1000) -- 1 sec

-- or connect to a unix domain socket file listened
-- by a redis server:
-- local ok, err = red:connect("unix:/path/to/redis.sock")

local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
    ngx.say("failed to connect: ", err)
    return
end

function set_to_cache(key,value,exptime)
    if not exptime then
            exptime = 0
    end
    local cache_ngx = ngx.shared.caceh_ngx
    local succ,err,forcible = cache_ngx:set(key,value,exptime)
    return succ
end

function get_from_cache( key )
    local cache_ngx = ngx.shard.cache_ngx
    local value = cache_ngx:get(key)

    if not value then
        value = get_from_redis(key)
        set_to_cache(key,value)
    end
    return value
end

function get_from_redis( key )
    local res,err = red:get(key)
    if res then 
            return 'yes'
    else
            return 'no'
    end
end

local res = get_from_redis('dog')
ngx.say(res)

(4)压力测试!
使用 get_from_redis 结果:

ab -n 100000 -c 100 http://127.0.0.1:8080/get_value

使用 get_from_cache,使用前需要在nginx.conf 的http中配置

 #openresty的缓存设置
  lua_shared_dict cache_ngx 128m;

重启openresty !



如果您觉得这篇博文对你有帮助,请点个赞,谢谢!


如果帅气(美丽)、睿智(聪颖),和我一样简单善良的你看到本篇博文中存在问题,请指出,我虚心接受你让我成长的批评,谢谢阅读!
祝你今天开心愉快!


欢迎访问我的csdn博客,我们一同成长!

不管做什么,只要坚持下去就会看到不一样!在路上,不卑不亢!

博客首页http://blog.csdn.net/u010648555

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/121122.html原文链接:https://javaforall.net

(0)
上一篇 2022年2月26日 下午10:00
下一篇 2022年2月26日 下午10:00


相关推荐

  • 多参数sp_executesql 函数的使用范例

    多参数sp_executesql 函数的使用范例终于搞定sp_executesql包含输出的多参数的调用,网上竟然没有很好的参考   set@sql=Nselect@I_ZSL=sum(I_SL),@I_ZYZ=sum(I_YZ),@I_ZZJ=sum(I_LJZJ),@I_ZJZ=(sum(I_YZ)-sum(I_LJZJ))fromV_GZ_SGZ_GZINFO_TYBwhereV_DW_DM=

    2022年5月21日
    47
  • 一文看懂TVS二极管SM8S30A

    一文看懂TVS二极管SM8S30A一文读懂TVS二极管SM8S系列,汽车抛负载防护器件随着汽车行业的大力发展,智能化、数字网络化、总线化以及节能环保成为了汽车发展的方向,然而,无论朝着哪种方向发展,汽车运用的基础电子保护防护元器件作用不容忽视,不可替代。如今,汽车电路保护的概念,早已不在局限于汽车保险丝,从仪表盘到车灯,从动力总成系统到高级驾驶辅助,个性化驾驶习惯和不确定的工作环境,都需要更高级、先进的保护措施为汽车保驾护航。电…

    2026年2月26日
    7
  • f stream_Streaming

    f stream_Streamingc++文件流基本用法
    C++学习笔记2010-05-2015:07:46阅读57评论0  字号:大中小 订阅
    c++的文件流处理其实很简单,前提是你能够理解它。文件流本质是利用了一个buffer中间层。有点类似标准输出和标准输入一样。
      c++IO的设计保证IO效率,同时又兼顾封装性和易用性。本文将会讲述c++文件流的用法。
      有错误和疏漏的地方,欢迎批评指证。
      需要包含的头文件:
      名字空间:std

    2026年1月23日
    4
  • Java虚拟机:class类文件结构

    Java虚拟机:class类文件结构

    2021年9月26日
    42
  • 需求规格说明书模板

    需求规格说明书模板需求规格说明阐述一个软件系统必须提供的功能和性能以及它所要考虑的限制条件,它不仅是系统测试和用户文档的基础,也是所有子系列项目规划、设计和编码的基础。它应该尽可能完整地描述系统预期的外部行为和用户可视化行为。除了设计和实现上的限制,软件需求规格说明不应该包括设计、构造、测试或工程管理的细节。  1)采用软件需求规格说明模版:采用需求规格说明书模板在你的组织中要为编写软…

    2022年4月9日
    70
  • UML图:用例图详细介绍

    UML图:用例图详细介绍用例图简介用例图用例图应用在软件开发的需求分析阶段 他描述了系统的功能以及如何使用一个系统用例图显示谁将是相关的用户 用户希望系统提供什么服务以及用户需要为系统提供的服务用例图最常用来描述系统以及子系统用例图分为业务用例图和系统用例图用例图的组成用例图主要包含以下 6 个元素参与者 Actor 用例 UseCase 关联关系 Association 包含关系 Include 扩展关系 Extend 泛化关系 Generalizati 1 参与者参与者的概念

    2026年3月18日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号