最終代碼請訪問 https://github.com/bill080307/ipfsgw,配合 openresty 效果更佳.
訪問 http://ipfs-gateway.dlimba.top:8082/ipns/QmXidpbD1osmHXWN4gJc3NHry3kzTnicnp9Utrpxk6s4Du/ 體驗效果
可以嘗試訪問https://ipfs.io/ipns/QmXidpbD1osmHXWN4gJc3NHry3kzTnicnp9Utrpxk6s4Du/ 非常慢。
在IPFS應用開發過程中,遇到了一個問題,IPNS查詢是在是太慢。
長達60秒的查詢時間,讓人受不了,對於開發和調試來說簡直是噩夢。
我打算週期性的獲取IPNS對應的IPFS地址,存入redis中,nginx在訪問ipns地址時重定向到ipfs地址上
- 結構圖
GET /ipfs/ 直接代理到ipfs gateway的8080端口的/ipfs/上
GET /ipns/ nginx 先查詢redis上是否有記錄,如果有代理到ipfs gateway的8080端口的/ipfs/上,如果沒有代理到ipfs gateway的8080端口的/ipns/上
數據庫還是打算使用json。並且可以和上一篇《自定義儲存固定器》複用同一個json文件。
- nginx 配置
lua_package_path "/usr/local/lib/lua/?.lua;;";
server {
listen 8082;
server_name _;
root /var/www/html;
index index.html;
location /ipfs/ {
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:8080/ipfs/;
}
location /ipns/ {
proxy_set_header Host $http_host;
set $path "";
rewrite_by_lua '
local request_uri = ngx.var.request_uri
local path = string.sub(request_uri, 7)
local f = string.find(path, "/")
if not f then
ipns = path
else
ipns = string.sub(path,0,f-1)
end
local redis = require "resty.redis"
local cache = redis.new()
local ok, err = cache.connect(cache, "127.0.0.1", "6379")
cache:set_timeout(60000)
if not ok then
ngx.var.path = "ipns/"..path
return
end
local res, err = cache:get(ipns)
if ngx.null ~= res then
ngx.var.path = "ipfs/"..string.gsub(path, ipns, res)
else
ngx.var.path = "ipns/"..path
end
';
proxy_pass http://127.0.0.1:8080/$path;
}
}
- cache
#!/usr/bin/python3
import ipfshttpclient
import json
import os
import redis
api = ipfshttpclient.connect('/ip4/127.0.0.1/tcp/5001', timeout=1200)
path = os.path.join(os.path.split(os.path.realpath(__file__))[0], 'data')
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
def loadjson(jsonfile):
with open(jsonfile) as json_file:
data = json.load(json_file)
return data
if __name__ == '__main__':
files = os.listdir(path)
for item in files:
if item == 'videoshare.json':
data = loadjson(os.path.join(path, item))
for k1, v1 in data['users'].items():
h = api.name.resolve(v1)
r.set(v1, h['Path'][6:])
- 定時運行cache
# m h dom mon dow user command
*/30 * * * * root cd /opt/ipfscache;python3 cache.py
最後完成的效果圖
將60秒優化到0.6秒
也歡迎大家訪問我維護的ipfs網關 http://ipfs-gateway.dlimba.top:8082/ipfs/hash