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


相关推荐

  • 游戏 fd和Player

    游戏 fd和Player

    2021年8月18日
    70
  • 面试又给我问到MySQL索引,最全的一次整理

    面试又给我问到MySQL索引,最全的一次整理

    2022年2月15日
    38
  • 服务器版dll修复工具,dll修复工具「建议收藏」

    服务器版dll修复工具,dll修复工具「建议收藏」winmm.dll是Windows多媒体相关应用程序接口,用于低档的音频和游戏手柄,缺少它可能造成部分软件无声音。当你的电脑提示“丢失winmm.dll”或者“没有找到winmm.dll”等类似错误信息。如果sqlite3.dll系统文件丢失、损坏,自行寻找选择适合系统的DLL系统文件,不但麻烦,还得冒着系统异常的风险。无主之地、荣誉勋章等游戏所需的physxcudart_20.Dll下载,解压后…

    2022年6月1日
    181
  • nfc怎么复制门禁卡,相关教程在这里

    nfc怎么复制门禁卡,相关教程在这里  在生活中小区、学校都有门禁的,为了保证安全,每一次都要刷门禁卡才能进去,但有时忘记了或者丢了怎么办呢,拉下来看看相关教程。  当然,不是所有的门禁卡都能模拟,所以我们就需要了解你的门禁卡是否是能模拟的类型。  门禁卡一般分为:ID卡和IC卡。而EM卡、M1卡、CPU卡等等,都是这两种卡的细分。  我们看上面这张图。在这张图中,卡是按工作频率来分的:ID卡的工作频率为125KHz频率,而IC卡的工作频率为13.56MHz以上。显然看出,因为IC卡的频率高,所以,它的安全性比较高。小区基本上选择

    2022年5月11日
    155
  • Java网页版仿QQ实现在线聊天功能(附带源码)[通俗易懂]

    Java网页版仿QQ实现在线聊天功能(附带源码)[通俗易懂]疫情期间,整天闷在家里又不能聚会,大把的空余时间差点让我发霉,后来有个客户发来新年祝贺,情不自禁想起了一件事情,就是他曾经提起过,要是在后台管理系统里面整合个聊天功能该多好啊,有了这个念头,马上行动起来!!!一.系统演示1.1聊天窗体主界面演示1.2模拟两人在线聊天(点击图片查看演示视频)1.3在线演示(真实系统展示)在线演示,点击进入系统到这里,若是您想要的,接下来听我娓娓道来↘↘二.开发工具开发软件:JDK7.0、MyEclipse2014数据库:MySQL5.6服

    2022年5月15日
    45
  • 构建基于Javascript的移动web CMS——加入jQuery插件

    构建基于Javascript的移动web CMS——加入jQuery插件

    2022年2月1日
    66

发表回复

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

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