在此先把前面自己做的那個功能在此分享下,是一個模仿淘寶的,希望大神們有什么想法可以不吝賜教:
自己是通過前面的參考配置lua與nginx的結合使用,利用腳本語言lua的強大特性和nginx的特性來實現這個功能,在nginx.conf的配置文件中加入如下代碼:
server { listen 22222; server_name localhost; # server_name somename alias another.alias; location /images/{ alias /root/images; set $image_root /root; set $file $image_root$uri; content_by_lua ' ngx.header.content_type = "text/plain"; ngx.say(ngx.var.file); '; } location /lua{ set $test "hello, world."; content_by_lua ' ngx.header.content_type = "text/plain"; ngx.say(ngx.var.test); '; } location /group1/M00 { alias /usr/local/servers/data/fdfs/data; set $image_root "/usr/local/servers/data/fdfs/data"; # alias /root/images; # set $image_root "/root/images"; if ( $uri ~ "/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/(.*)" ) { set $image_dir "$image_root/$3/$4"; set $image_name "$5"; set $file "$image_dir/$image_name"; } # content_by_lua ' # ngx.header.content_type = "text/plain"; # ngx.say(ngx.var.image_dir); # ngx.say(ngx.var.image_name); # ngx.say(ngx.var.file); # '; if ( !-f $file ) { # 關閉lua代碼緩存,方便調試lua腳本 #lua_code_cache off; content_by_lua_file "/usr/local/servers/lua/convert.lua"; } ngx_fastdfs_module; } # location ~ /group[1-3]/M00{ # root /usr/local/servers/data/fdfs/data; #/fdfs/storage/data; # ngx_fastdfs_module; # } }
這里面利用了nginx的正則表達式,正則表達式是相當強悍的,可以得到你需要訪問的uri的值。
然后再convert.lua中寫入如下代碼:
local area = nil local originalUri = ngx.var.uri; local originalFile = ngx.var.file; local index = string.find(ngx.var.uri, "([0-9]+)x([0-9]+)"); if index then originalUri = string.sub(ngx.var.uri, 0, index-2); area = string.sub(ngx.var.uri, index); index1 = string.find(area, "([.])"); area1 = string.sub(area, 0, index1-1); local index2 = string.find(originalFile, "([0-9]+)x([0-9]+)"); originalFile1 = string.sub(originalFile, 0, index2-2) end local image_sizes = {"80x80", "800x600", "40x40", "60x60"}; function table.contains(table, element) for _, value in pairs(table) do if value == element then return true end end return false end if table.contains(image_sizes, area1) then local command = "/usr/bin/gm convert " .. originalFile1 .. " -thumbnail " .. area1 .. " -background gray -gravity center -extent " .. area1 .. " " .. ngx.var.file; os.execute(command); end;
~差不多這樣就可以實現功能了,通過訪問可以實現比率壓縮,因為在上班時間暫時就這么寫下了,目前的一個工作還有很多功能需要實現,如有看不懂的可以留言,大神們可以指教,謝謝!
參考:http://www.v2ex.com/t/113845
http://blog.sina.com.cn/openresty
http://write.blog.csdn.net/postedit
https://github.com/azurewang/lua-resty-fastdfs/blob/master/lib/resty/fastdfs/storage.lua
http://wiki.nginx.org/HttpLuaModule