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

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

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • 股票预测 lstm(时间序列的预测步骤)

    LSTM数据集实战如果对LSTM原理不懂得小伙伴可以看博主下一篇博客,因为博主水平有限,结合其他文章尽量把原理写的清楚些。数据集首先附上数据集链接:https://pan.baidu.com/s/1AKsz-ohmYHr9mBEEh76P5g提取码:6owv这个数据集是关于股票的,里面有日期,开盘价等信息。既然是时间序列预测,我们最关心的是预测值在时间维度上的走势如何,那我们只要最后一列volume和第一列date这两列就好了。实战先是导入相关包,一些常见的包就不详细说了,我们需要的Se

  • ETH显卡矿机_eth矿机组装

    ETH显卡矿机_eth矿机组装显卡矿机搭建选择合适显卡选择硬件选择挖矿软件挖矿系统mineros挖矿软件注意:每个币种的软件都不一样挖矿系统和软件也有多种具体对应的官网都会有教程选择合适显卡主流显卡算力对比选择硬件选择挖矿软件前提准备自己的钱包地址选择矿池地址挖矿系统mineros步骤:注册账号刻盘启动挖矿和监控矿机状态挖矿软件NBMiner…

  • @MapperScan 源码解析

    @MapperScan 源码解析aa

  • 不装了、摊牌了,我们要搞事情

    不装了、摊牌了,我们要搞事情一起在技术的海洋里狗刨~

  • pycahrm 激活码_在线激活

    (pycahrm 激活码)好多小伙伴总是说激活码老是失效,太麻烦,关注/收藏全栈君太难教程,2021永久激活的方法等着你。IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.cn/100143.htmlCJM5ZJBPHS-eyJsaWNlbnNlSWQi…

  • CreateProcess和WinExec

    CreateProcess和WinExecCreateProcess非阻塞运行,而WinExec为阻塞运行,它非要等到返回时才继续执行。在两个进程共享同一个端口时,为了能让一个退出另一个申请,必须用函数CreateProcess,等到我的端口资源释放后,在运行另一个进程进行申请

发表回复

您的电子邮箱地址不会被公开。

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