2020-07-21

#### nginx缓存预热与读取

##### 缓存预热


首先,连接mysql ,按照广告分类ID读取广告列表,转换为json字符串

然后,连接redis,将广告列表json字符串存入redis 。

请求:

  /ad_update

参数:

  position  ‐‐指定广告位置

返回值:

  json

在/root/lua目录下创建ad_load.lua ,实现连接mysql 查询数据 并存储到redis中

```lua

ngx.header.content_type="application/json;charset=utf8"

local cjson = require("cjson")  #获取请求Json数据

local mysql = require("resty.mysql")  #获取mysql数据库连接对象

local uri_args = ngx.req.get_uri_args()  #获取uri的参数

local position = uri_args["position"]  #获取参数中的position字段

local db = mysql:new()   

db:set_timeout(1000) 

local props = {       #设置数据库连接参数

    host = "192.168.200.128", 

    port = 3306, 

    database = "changgou_business", 

    user = "root", 

    password = "root" 

}

local res = db:connect(props)   #连接数据库

local select_sql = "select url,image from tb_ad where status ='1' and position='"..position.."' and start_time<= NOW() AND end_time>= NOW()"  #定义sql语句

res = db:query(select_sql)  #执行查询

db:close()  #关闭数据库连接

local redis = require("resty.redis")  #获取redis连接对象

local red = redis:new()

red:set_timeout(2000)

local ip ="192.168.200.128"

local port = 6379

red:connect(ip,port)  #连接数据库

red:set("ad_"..position,cjson.encode(res))  #将数据缓存到redis中

red:close()  #关闭redis

ngx.say("{flag:true}")  #响应客户端

```

修改/usr/local/openresty/nginx/conf/nginx.conf文件:

代码如下:

```

  #user  nobody;

user root root;

worker_processes  1;

#error_log  logs/error.log;

#error_log  logs/error.log  notice;

#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {

    worker_connections  1024;

}

http {

    include       mime.types;

    default_type  application/octet‐stream;

    sendfile        on;

    #tcp_nopush     on;

    #keepalive_timeout  0;

    keepalive_timeout  65;

    #gzip  on;

    server {

        listen       80;

        server_name  localhost;

        charset utf‐8;

        #access_log  logs/host.access.log  main;

        # 添加

        location /ad_update {  #关联请求路径和lua脚本路径

            content_by_lua_file /root/lua/ad_update.lua;

        }


        # redirect server error pages to the static page /50x.html

        #

        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   html;

          }       

    }

}

```

重新启动 nginx

测试:http://192.168.200.128/ad_update?position=web_index_lb

##### 广告缓存读取

实现思路:

通过lua脚本直接从redis中获取数据即可

定义请求:

请求 :/ad_read

参数:position

返回值:json

在/root/lua目录下创建ad_read.lua

```lua

ngx.header.content_type="application/json;charset=utf8"

local uri_args = ngx.req.get_uri_args();  #获取uri参数

local position = uri_args["position"];  #获取参数中position字段

local redis = require("resty.redis");

local red = redis:new()

red:set_timeout(2000)

local ok, err = red:connect("192.168.200.128", 6379) #连接redis

local rescontent=red:get("ad_"..position)

ngx.say(rescontent)

red:close()

```

在 /usr/local/openresty/nginx/conf/nginx.conf中server下添加配置

```

location /ad_read {    #关联请求路径和lua脚本路径

  content_by_lua_file /root/lua/ad_read.lua;

}

```

测试 http://192.168.200.128/ad_read?position=web_index_lb 输出

```json

[{"url":"img\/banner1.jpg","image":"img\/banner1.jpg"},

{"url":"img\/banner2.jpg","image":"img\/banner2.jpg"}]

```

#### 二级缓存-加入openresty本地缓存

流程示意图:


如上的方式没有问题,但是如果请求都到redis,redis压力也很大,所以我们一般采用多

级缓存的方式来减少下游系统的服务压力。

先查询openresty本地缓存 如果没有再查询redis中的数据

**openresty中自带了nginx,所以安装了openresty后直接使用里面的nginx就能使用openresty本地缓存**

修改 /root/lua目录下ad_read文件, 内容如下:

```lua

ngx.header.content_type="application/json;charset=utf8"

local uri_args = ngx.req.get_uri_args();

local position = uri_args["position"];  #获取请求参数中position

local cache_ngx = ngx.shared.dis_cache; #获取本地缓存(openresty)

#从本地缓存openresty中获取position

local adCache = cache_ngx:get('ad_cache_'..position);

#如果获取的数据是空的,那么就去redis中获取

if adCache == "" or adCache == nil then

local redis = require("resty.redis");    

local red = redis:new()    

red:set_timeout(2000)    

local ok, err = red:connect("192.168.200.128", 6379)    

local rescontent=red:get("ad_"..position)    

ngx.say(rescontent)    

red:close()    

    #然后将从redis中获取的数据再缓存到本地缓存openresty中

cache_ngx:set('ad_cache_'..position, rescontent, 10*60);    

else

  ngx.say(adCache)   

end

```

修改 nginx配置文件vi /usr/local/openresty/nginx/conf/nginx.conf ,http节点下添加配置 :

```lua

#包含redis初始化模块

lua_shared_dict dis_cache 5m;  #共享内存开启

```

具体位置如下:


#### 前端页面实现(了解)

修改index.html,编写脚本

加一段JS代码:

```html

<script>

   new Vue({    

        el: '#app',

        data: {

            ad: {

web_index_lb:[]                

}            

        },

        methods: {

            adRead: function(position) {

axios.get('ad_read? position='+position).then(response =>{                

this.ad[position]=response.data                                      

})                

            }

        },

created(){        

this.adRead('web_index_lb')            

}        

      })

</script>

```

在页面上添加

```html

<div id='app'> ... </div>

```

修改index.html,渲染广告轮播图

```html

<div id="myCarousel" data‐ride="carousel" data‐interval="4000"

class="sui‐carousel slide">

<ol class="carousel‐indicators">    

<li data‐target="#myCarousel" data‐slide‐to="0" class="active" v‐

for="item in ad.web_index_lb"></li>


</ol>    

<div class="carousel‐inner" id="lbt">    

<div class="item" v‐for="item in contentList">        

<a :href="item.url">            

<img :src="item.pic"  />            

  </a>        

</div>               

</div>    

<a href="#myCarousel" data‐slide="prev" class="carousel‐control

left">‹</a>


<a href="#myCarousel" data‐slide="next" class="carousel‐control

right">›</a>


</div>

```

上传至服务器并测试

更改

```html

# 加载首页

        location / {

            root   html;

            index  index.html index.htm;

        }

```

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,753评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,668评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,090评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,010评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,054评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,806评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,484评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,380评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,873评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,021评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,158评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,838评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,499评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,044评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,159评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,449评论 3 374
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,136评论 2 356

推荐阅读更多精彩内容