最终代码请访问 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