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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • c++ auto类型_auto C++

    c++ auto类型_auto C++编程时候常常需要把表达式的值付给变量,需要在声明变量的时候清楚的知道变量是什么类型。然而做到这一点并非那么容易(特别是模板中),有时候根本做不到。为了解决这个问题,C++11新标准就引入了auto类型说明符,用它就能让编译器替我们去分析表达式所属的类型。和原来那些只对应某种特定的类型说明符(例如int)不同。auto让编译器通过初始值来进行类型推演。从而获得定义变量的类型,所以说auto定义的变量必须有初始值。有的时候我们还会遇到这种情况,我们希望从表达式中推断出要定义变量的类型,但却不想用表达式

    2022年9月9日
    0
  • 湖北第二师范学院计算机学院考研率,22考研全面数据解析你报考的地区到底有多难?…

    湖北第二师范学院计算机学院考研率,22考研全面数据解析你报考的地区到底有多难?…原标题:22考研全面数据解析你报考的地区到底有多难?我国的硕士研究生报考人数年年激增,屡创新高,2019年达到290万人,2020年首次突破300万人,达到341万人,按照这样的考研趋势,2021年报考人数突破400万人也是极有可能的。从历年的数据来看,自2015年起,报名人数的增长率都在不断增大,2020年的增长率相对2019年降低了4.21%,但是报名人数实际上都是增加了50多万。考研热度每…

    2022年5月6日
    308
  • 【Android】Android加密和解密方式

    【Android】Android加密和解密方式一、不可逆加密不可逆加密算法的特征是加密过程中不需要使用密钥,输入明文后由系统直接经过加密算法处理成密文,这种加密后的数据是无法被解密的,只有重新输入明文,并再次经过同样不可逆的加密算法处理,得到相同的加密密文并被系统重新识别后,才能真正解密。如信息摘要(MessageDigest)和安全散列(SecureHash)算法属于此类,常见的算法包括MD5、SHA1、PBKDF2、bcrypt等。特点:使用MD5和SHA进行加解密://MD5加密privatestaticStringt

    2022年5月17日
    43
  • linux中mysql忘记密码[通俗易懂]

    linux中mysql忘记密码[通俗易懂]第一种解决方案解决方法:1、利用“servicemysqlstop”命令关闭mysql服务;2、修改mysql的配置文件“my.conf”;3、用“servicemysqldstart”命令重启数据库;4、用“usemysql”语句修改密码。本教程操作环境:linux7.3系统、mysql8.0.22版本、DellG3电脑。linux中mysql忘记密码怎么解决解决方法:1、检查mysql服务是否启动,如果启动,关闭mysql服务 .

    2022年6月25日
    27
  • 获取窗口句柄 c语言,VC++编程获取窗口句柄的方法小结分享「建议收藏」

    获取窗口句柄 c语言,VC++编程获取窗口句柄的方法小结分享「建议收藏」—-想了解VC++编程获取窗口句柄的方法小结分享的全部内容且更多的C语言教程关注VC++编程获取窗口句柄的方法小结分享实例讲述了VC++编程获取窗口句柄的方法。分享给大家供大家参考,具体如下:在VC++编程中常需获取控件或窗体句柄,下面总结了几种方法,还希望大家能多多补充。1、自身窗口句柄可用AfxGetMainWnd获取。2、系统中其他APP的窗口句柄可用FindWindow获取(用SPY帮一下…

    2022年7月21日
    10
  • 安全工具-Sparta

    安全工具-SpartaSparta是一个集端口扫描、网络扫描、服务探测以及暴力激活成功教程等多项功能于一身的工具,kali中已经预装了该工具,可直接使用。  >输入目标IP,开始扫描即可探测出开放的端口及服务  >选中ssh服务,对其进行暴力激活成功教程  >确认IP地址、端口、扫描服务等,上传用户名-密码字典后Run  >查看扫描log,探测出一个密码被激活成功教程Hydrav8.2(c…

    2025年6月9日
    0

发表回复

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

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