• openresty + lua 2、openresty 连接 redis,实现 crud


      redis 的话,openresty 已经集成,ng 的话,自己引入即可。

      github 地址:https://github.com/openresty/lua-resty-redis

      github 里提供有详细的教程,按照教程来应该是不会有问题的。redis 我也简单写了一个工具类,具体贴上我的一系列代码吧.大神勿喷.

     

      工具类:(很基础,重点是自己去写,只是针对初学者,大神忽视即可)

    local connectRedisUtil = {}
    
    local redis = require "resty.redis"
    -- or connect to a unix domain socket file listened
    -- by a redis server:
    --     local ok, err = red:connect("unix:/path/to/redis.sock")
    
    function connectRedisUtil.connectRedis() 
        local red = redis:new()
        red:set_timeout(1000) -- 1 sec
    
        local ok, err = red:connect("127.0.0.1", 6379)
        if not ok then
            ngx.say("failed to connect: ", err)
            return false
        end
        
        return red
    end
    
    return connectRedisUtil
    View Code

      调用:

    local connectRedisUtil = require("connectRedisUtil")
    local red = connectRedisUtil.connectRedis()
    if red == false then
        ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
        return
    end
    
    --set
    local ok, err = red:set("englishName", "Allen")
    if not ok then
        ngx.say("set bad result:", err)
        return
    end
    
    --get
    local res, err = red:get("englishName")
    if not res then
        ngx.say("get englishName failed:", err)
        return
    end
    ngx.say("englishName is : ", res)
    
    res, err = red:get("name")
    if not res then
        ngx.say("get bad result:", err)
        return
    else
        ngx.say("res is :", res)
    end
    View Code

      openresty 配置:

    server {
        listen 6688;
        server_name localhost;    
        default_type "text/html";
    
        lua_need_request_body on;
    
        location = /test_redis_exercise {
            content_by_lua_file /Users/zhuzi/zhuzi_relation/exercise/lua_pro/redis_exercise.lua;
        }
    }
    View Code

      
      OK,搞定。接下来打开浏览器验证一下吧。

      效果我就不贴了,肯定是没有问题的。今天的就到这里了。

  • 相关阅读:
    solr 简要笔记
    JQuery select 编程时选中原有的值
    java设计模式图
    java设计模式
    qq空间微博等更多社交平台分享
    API调用开发demo
    fastJson
    小程序开发
    史上最全的机器学习资料(上)
    大数据”学习资源(下)
  • 原文地址:https://www.cnblogs.com/zhuzi91/p/7880098.html
Copyright © 2020-2023  润新知