Java基础、中级、高级、架构面试资料

Openresty 网页加速教程

JAVA herman 2775浏览 0评论
公告:“业余草”微信公众号提供免费CSDN下载服务(只下Java资源),关注业余草微信公众号,添加作者微信:xttblog2,发送下载链接帮助你免费下载!
本博客日IP超过2000,PV 3000 左右,急需赞助商。
极客时间所有课程通过我的二维码购买后返现24元微信红包,请加博主新的微信号:xttblog2,之前的微信号好友位已满,备注:返现
受密码保护的文章请关注“业余草”公众号,回复关键字“0”获得密码
所有面试题(java、前端、数据库、springboot等)一网打尽,请关注文末小程序
视频教程免费领
腾讯云】1核2G5M轻量应用服务器50元首年,高性价比,助您轻松上云

使用多级缓存来减少数据库的访问达到加快网页的速度。但是随着用户的继续上涨,系统的压力越来越大。单一的缓存数据减少数据库的访问效果就不是特别的明显了。openresty 能够直接在nginx层直接对请求处理,而不需要每次都访问tomcat,从而减轻服务器的压力。本文介绍 openresty 的相关教程。

为了学习 openresty 我们准备了3台服务器,信息如下:

  • A:(深圳,Nginx环境,本地Redis,tomcat服务器)
  • B:(广州,tomcat服务器)
  • C:(北京,tomact服务器)

为了减少后端的相应时间,之前使用的是在应用里集成ehcache作为一级缓存,redis作为二级缓存。这种架构存在一种特殊的情况:当Nginx将首页的请求分发给北京节点的时候,响应将变得极其缓慢,用户的请求需要从深圳到北京,再从北京回到深圳,光是延时就要耗费40ms(最好的情况),由于网速是1M/s,最坏的情况下,响应用户的请求也得耗费几秒。所以,为了减少这种极端情况,设计了这款架构。

步骤:

  1. 请求到达nginx后,openresty通过lua读取本地缓存,如果不命中,则回源到tomcat集群。
  2. tomcat集群首先从自己的服务器中读取一级缓存Ehcache,如果没有命中,则继续回源到二级缓存。
  3. 读取二级缓存Redis,如果依旧没有命中,则回源到MySQL服务器。

Openresty

安装过程可以直接参考官方文档:http://openresty.org/cn/download.html,安装前还需安装以下开发库:

yum install pcre-devel openssl-devel gcc curl

然后进行编译安装:

tar -xzvf openresty-VERSION.tar.gz
cd openresty-VERSION/
./configure
make
sudo make install

Nginx 相关配置

Openresty自带了Nginx。所以,只要安装好了Openresty,即可直接使用nginx来配置。以下只是部分,需要全部的请查看 mynginxconfig.ngx

http {
    include       mime.types;
    default_type  application/octet-stream;
    # 需要添加lua的相关库
    lua_package_path "/opt/openresty/lualib/?.lua;;";
    lua_package_cpath "/opt/openresty/lualib/?.so;;";
    ...
	# 业余草:www.xttblog.com
    access_log  logs/access.log  main;
    sendfile        on;
    keepalive_timeout  65;
	# 业余草:www.xttblog.com
    upstream backend {
        #consistent_hash was not configured
        hash $uri;
        server 47.95.10.139:8080;
        server 119.23.46.71:8080;
        server 119.29.188.224:8080;
    }
    server {
        listen       80;
        server_name  www.wenzhihuai.com;
        # 精确匹配,打开首页的时候进入
        location  = / {
            default_type    text/html;
            root   html;
            index  index.html index.htm;
            ...
            # 关闭缓存lua脚本,调试的时候专用
            lua_code_cache off;
            content_by_lua_file /opt/lua/hello.lua;
            # 此处不要proxy_pass了,否则lua脚本没用
            # proxy_pass http://backend;
			# 业余草:www.xttblog.com
        }
        # 如果上面的不符合,则匹配下面的
        location / {
            default_type    text/html;
            root   html;
            index  index.html index.htm;
            # 对请求进行反向代理
            proxy_pass http://backend;
        }
    }
    ...
}

lua 脚本

脚本记得放在 /opt/lua/hello.lua 目录下,对应 nginx 的配置,同时需要引入 redis 模块。

local redis = require "resty.redis"
local red = redis:new()
-- 业余草:www.xttblog.com
local request_uri = ngx.var.request_uri
-- 业余草:www.xttblog.com
if (request_uri == "/" or request_uri == "/index.html") then
    red:set_timeout(1000) -- 1 sec
    red:connect("119.23.46.71", 6340)
    local ok, err = red:auth("root")
    if not ok then
        ngx.say("failed to connect: ", err)
        return
    end
    --缓存的首页放在key为index里
    local resp, errr = red:get("index")
    if not resp then
        return
    end
    if resp == ngx.null then
        resp = "<h1>hello world</h1>"
    end
    --如果找到,则输出内容
    ngx.print(resp)
    red:close()
    return
end
local pagenum = ngx.req.get_uri_args()["pagenum"]
--因为在nginx中设置了proxy_pass_request_headers off,即不讲请求头部传到lua,所以头部需要重新设置
ngx.req.set_header("Accept", "text/html,application/xhtml+xml,application/xml;")
--这里回源到tomcat的时候,Accept-Encoding默认为gzip,即返回来数据已经是gzip压缩过了的,返回到用户的时候又被压缩了一次,会造成一堆乱码。所以将Accept-Encoding设置为空。
ngx.req.set_header("Accept-Encoding", "")
local respp = ngx.location.capture("/index.do", { method = ngx.HTTP_GET, args = { pagenum = pagenum } })
--打印
ngx.print(respp.body)
return

更新首页到 redis

每隔20秒直接访问后端进行首页的抓取,然后存储到redis里面,简单粗暴。

@Controller
@SuppressWarnings("unchecked")
public class TimeController {
    //logger
    private static final Logger logger = LoggerFactory.getLogger(TimeController.class);
    @Scheduled(cron = "0/20 * * * * ?")
    public void refreshIndex() throws Exception {
        String ip = IPUtils.getServerIp().replaceAll("\n", "");
        if (REGULARIP.equals(ip)) {
            String content = HttpHelper.getInstance().get("http://119.29.188.224:8080");
            JedisUtil.getInstance().set("index", content);
        }
    }
}

以上就是总结了我在实际应用中对 Openresty 的使用,如有不懂欢迎留言,或加作者微信公众号:业余草/yeyucao。

业余草公众号

最后,欢迎关注我的个人微信公众号:业余草(yyucao)!可加作者微信号:xttblog2。备注:“1”,添加博主微信拉你进微信群。备注错误不会同意好友申请。再次感谢您的关注!后续有精彩内容会第一时间发给您!原创文章投稿请发送至532009913@qq.com邮箱。商务合作也可添加作者微信进行联系!

本文原文出处:业余草: » Openresty 网页加速教程