2017-05-18 97 views
0

我想在我的nodejs應用程序中打開maxmind opensource數據庫。我的應用程序接收來自Java應用程序的IP地址列表。應用程序然後返回對應於每個IP的經度和緯度。我已經成功完成了這個同步,但我想異步做它使事情變得更快一點。我爲此編寫了一個代碼,但應用程序每次都會被終止。我猜測,原因可能是同時打開同一個數據庫(我可能是錯的:D)。我張貼下面的代碼。請看看它,並就我的錯在哪裏提出一些建議。謝謝!!!在Nodejs中打開Maxmind db

app.post('/endPoint', function(req, res){ 
var obj = req.body; 
var list = []; 
var ipList = obj.ipList; 
for(var i = 0; i<ipList.length; i++){ 
var ip = ipList[i]; 
//console.log(i); 
maxmind.open('./GeoLite2-City.mmdb', function(err, cityLookup){ 
if(err) throw err; 
console.log("open database"); 
var city = cityLookup.get(ip); 
if(city!=null){ 
var cordinates = {'latitude': city.location.latitude, 'longitude': geodata.location.longitude}; 
     //console.log(cordinates); 
     list.push(cordinates); 
     } 
     if(list.length == ipList.length){ 
     res.json({finalMap: list}); 
     } 
}); 
} 
}); 

回答

0

您應該只打開一次數據庫,然後重新使用它。

最簡單的解決辦法是同步你的文件的頂部打開數據庫:

const maxmind = require('maxmind'); 
const cityLookup = maxmind.openSync('./GeoLite2-City.mmdb'); 

閱讀它異步不會加快東西一大堆,而且由於裝載數據庫完成只有一次(在應用程序啓動過程中),我認爲這可能會暫時阻止事件循環幾秒鐘,這不是什麼大事。

而在你的請求處理程序使用cityLookup功能:

app.post('/endPoint', function(req, res) { 
    ... 
    let city = cityLookup.get(ip); 
    ... 
}); 
+0

嘿!感謝你的回答。通過一次打開數據庫,它確實運行得更快。 –