zoukankan      html  css  js  c++  java
  • openresty 的小白记录

    openresty提供了一个快速访问数据库,快速响应的功能。基于lua + redis,我们可以做到快速响应,达到10k级连接的处理能力。

    openresty 的小白记录

    好的学习资料,从lua到openresty

    https://moonbingbing.gitbooks.io/openresty-best-practices/content/openresty/simple_api.html

    基础类型

    布尔类型,可选值 true/false;Lua 中 nil 和 false 为“假”,其它所有值均为“真”。比如 0 和空字符串就是“真”;
    在 Lua 中,函数 也是一种数据类型,函数可以存储在变量中,可以通过参数传递给其他函数,还可以作为其他函数的返回值。
    Table 类型实现了一种抽象的“关联数组”。“关联数组”是一种具有特殊索引方式的数组,索引通常是字符串(string)或者 number 类型,但也可以是除 nil 以外的任意类型的值。

    函数的参数

    lua函数的参数大部分是按值传递的
    当传值是table是,则是引用关系,除此之外,都是按值传递参数
    允许多个返回值,有点像scala的元组

    Lua UnPack函数用法实例,unpack它接受一个数组(table)作为参数,并默认从下标1开始返回数组的所有元素

    点号与冒号操作符的区别

    https://moonbingbing.gitbooks.io/openresty-best-practices/content/lua/dot_diff.html
    冒号操作会带入一个 self 参数,用来代表 自己。而点号操作,只是 内容 的展开。
    在函数定义时,使用冒号将默认接收一个 self 参数,而使用点号则需要显式传入 self 参数。

    nginx相关语法

    https://www.hi-linux.com/posts/4336.html

      access_by_lua_file  lua/access_check.lua;  校验参数
      content_by_lua_file lua/$1.lua;  执行lua脚本并返回content
      rewrite_by_lua_file 在access阶段前运行,主要用于rewrite重定向
    
      ngx.exit(ngx.HTTP_BAD_REQUEST) 
      ngx.say(args.a * args.b)
      ngx.log(ngx.ERR, "failed to log message: ", err)
      ngx.log(ngx.ERR, "num:", num)
      ngx.log(ngx.INFO, " string:", str)
    
      local args = ngx.req.get_uri_args()
       ngx.say(args.a * args.b)
    
      ngx.var.arg_a
    
       ngx.location.capture  子请求
    
       lua_code_cache 默认打开
    
       local fp = require("my")
    

    内置绑定变量

    https://moonbingbing.gitbooks.io/openresty-best-practices/content/openresty/inline_var.html

    共享变量

    ngx.ctx 表就是为了解决这类问题而设计的
    每个请求,包括子请求,都有一份自己的 ngx.ctx 表,相互隔离,子请求和其他请求间也是隔离的

    防止sql注入

    https://moonbingbing.gitbooks.io/openresty-best-practices/content/openresty/safe_sql.html

    利用 cosocket 发起子请求

    https://moonbingbing.gitbooks.io/openresty-best-practices/content/openresty/how_request_http.html

    share内存

    多个worker共享的内存
    lua_shared_dict
    lua_shared_dict logs 100m;

    local domaindb = ngx.shared.domaindb

    pcall

    protect call

    demo

    start

    cd ~/work
    mkdir conf
    mkdir lua
    mkdir logs
    
    nginx -p `pwd`/ -c conf/nginx.conf 
    

    nginx.conf

    	worker_processes  1;
    	error_log logs/error.log;
    	events {
    	    worker_connections 1024;
    	}
    	http {
    
    
    	    lua_code_cache off;
    
    	    lua_shared_dict datas 100m;
    
    	    server {
    	        listen 8080;
    	        server_name opentest2.com;
    	        location / {
    	            default_type text/html;
    	            set $yoxi DSX:$host;
    	            content_by_lua_file lua/index.lua;
    	        }
    	    }
    
    	    server {
    	        listen 8080;
    	        server_name opentest.com;
    	        location /test {
    	        content_by_lua_block {
    	            local redis = require "resty.redis"
    	            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
    	            end
    
    	            -- 请注意这里 auth 的调用过程
    	            local count
    	            count, err = red:get_reused_times()
    	            if 0 == count then
    	                
    	            elseif err then
    	                ngx.say("failed to get reused times: ", err)
    	                return
    	            end
    
    	            ok, err = red:set("dog", "an animal")
    	            if not ok then
    	                ngx.say("failed to set dog: ", err)
    	                return
    	            end
    
    	            ress = red:get("dog");
    	            -- ngx.say("set result: ", ress)
    	            ngx.redirect("http://opentest2.com:8080/index?from8082test")
    
    	            -- 连接池大小是100个,并且设置最大的空闲时间是 10 秒
    	            local ok, err = red:set_keepalive(10000, 100)
    	            if not ok then
    	                ngx.say("failed to set keepalive: ", err)
    	                return
    	            end
    	        }
    	    }
    	    }
    	}
    

    index.lua

    	local datas = ngx.shared.datas
    	local d_data = datas:get('a')
    	ngx.log(ngx.ERR,d_data)
    	datas:set('a','b',10)
    
    	if d_data == nil then
    	   d_data = 'a';
    	   ngx.log(ngx.ERR,'a is not exitts')
    	   datas:set('a', 'a', 10)
    	end  
    
    
    	local arg  = ngx.req.get_uri_args();
    
    
    	for k,v in pairs(arg) do
    	          ngx.say(datas:get('a'),'----dsxhost:----',ngx.var.yoxi,'
    ')
    	          ngx.print();
    	          ngx.say("====" .. ngx.var.host .. ngx.var.uri .. "?".. ngx.var.args .. "====")
    	          ngx.say("[GET23 ] key:", k, " v:", v)
    	end
    

    http模块上设置

    lua_code_cache on //线上必须打开,否则性能下降明显
    lua_share_dict local_cahce 100m //nginx本地缓存
    lua_package_path ""  //lua代码包路径
    
    upstream foo.example.com {
        server 127.0.0.1:8001 weight=5 max_fails=3 fail_timeout=10s;
    	server 127.0.0.1:8002 weight=10;
    	server 10.0.0.11:7070 backup;   //其他全部的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。
    	ip_hash;
    }
    

    server模块

    location / {

    	 content_by_lua_file{
    			local redis = require "resty.redis"
    			local red = redis:new()
    			red:setTimeout(1000)
    			local ok, err= red:connect("127.0.0.1", 6379)
    			if not ok then
    			   ngx.say("failed to connect: ",err);
    			   return;
    				
    			local flag = red:get(ngx.var.host)   
    			
    			red:set_keepalive(10000,100)
    			
    			if(flag == nil) then
    				ngx.redirect("/error.aspx")
    				return
    
    
    			ngx.ctx.result_domain = "shop.xx.com"
    				
    
    	}
        proxy_pass        http://ngx.var.result;
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    }	
    

    ngx.null is nil

    流程

    init
    rewrite
    access 
    content
    

    ngx.var需要预定义如

      location /foo {
    		set $a 12;
    		set $b '';
    		rewrite_by_lua_block {
    			ngx.var.b = tonumber(ngx.var.a) + 12;
    		}
    

    ngx.ctx作用于单个模块上下文

      content_by_lua_block {
    		ngx.ctx.result = ngx.ctx.foo
    		ngx.say(ngx.ctx.result)
    	}	
    

    ngx.var 是获取 Nginx 的变量,需要经历字符串 hash、hash 表查找等过程
    ngx.ctx 仅仅是一个 Lua table 而已,它的引用存放在 ngx_lua 的模块上下文(ctx_ref)
    使用 ngx.ctx 比 ngx.var 往往是更好的选择

    nginx模块含义

    http:全局配置
    server:虚拟主机
    location:是用来为匹配的 URI 进行配置,即php文件如何处理,html文件如何处理...

    OSI七层协议是什么

    应用层 HTTP FTP
    表示层 JPEG ASCll
    会话层
    传输层 TCP UDP PORT
    网络层 IP
    数据链路层
    物理层
    

    nginx 4层

    IP+端口级别,在OSI4层工作,不理解协议,实现流量的负载均衡

    nginx 7层

    http url级别应用层,除了支持4层以外,还有应用层的信息,如url,更加智能,如缓存图片,html

            local count
            count, err = red:get_reused_times()
            if 0 == count then
                ok, err = red:auth('xx')
                if not ok then
                    ngx.say("failed to auth: ", err)
                    return
                end
           elseif err then
                ngx.say("failed to get reused times: ", err)
                return
          end
  • 相关阅读:
    django组件,有分页器(重要的很)
    wusir的django
    git 生成ssh key
    阶乘问题的题解
    拱猪计分的题解
    子数整数的题解
    安全逃离的题解
    题解 P1262 【间谍网络】
    斗地主的题解
    鸭王的题解
  • 原文地址:https://www.cnblogs.com/windliu/p/10492566.html
Copyright © 2011-2022 走看看