定制化设计一站式临时空间解决方案
高端产品行业领先进口生产线
核心技术装配式移动建筑系统
在本文中,我们将自学如何用于Web3Js自动处置生产环境中的区块链插入。下面叙述的方法限于于Web3Js版本1.0.0-beta.35,但是对于平稳的1.2 *版本也限于。问题叙述如果您的团队在生产中用于Web3Js,那么您必需意识到在Web3Js中没内置的新的连接功能来处置区块链插入或重新启动。
因此,一般来说情况下,当相连下降时,必须重新启动NodeJS服务以便再度相连到区块链。这不是一个很简单的方法。解决方案让我们想到我们如何高雅地处置NodeJS中区块链插入的情况。
在Web3Js库中,程序为我们获取了以下事件相连——创建相连错误——程序错误完结——程序相连完结。断开连接后,我们可以利用中止事件重新启动一个新的Web3Js相连。让我们来看一个例子来解读这一点:File connection.js在这个文件中,我们将处置NodeJS和区块链之间的相连。我们将有一个新的区块链相连,它将回到一个Web3活动相连对象。
const web3 = require("web3");let hasProviderEnded = false, web3Instance, reconnectInterval = 10000; async function newBlockchainConnection(webSocketProvider, endCallback) { // create new provider const provider = new web3.providers.WebsocketProvider(webSocketProvider); hasProviderEnded = false; // connect event fires when the connection established successfully. provider.on('connect', () = console.log("connected to blockchain"));// error event fires whenever there is an error response from blockchain and this event also has an error object and message property of error gives us the specific reason for the error provider.on('error', (err) = console.log(err.message)); // end event fires whenever the connection end is detected. So Whenever this event fires we will try to reconnect to blockchain provider.on('end', async (err) = { // handle multiple event calls sent by Web3JS library if (hasProviderEnded) return; // setting hashProviderEnded to true as sometimes the end event is fired multiple times by the provider hasProviderEnded = true; // reset the current provider provider.reset(); // removing all the listeners of provider. provider.removeAllListeners("connect"); provider.removeAllListeners("error"); provider.removeAllListeners("end"); setTimeout(() = { // emitting the restart event after some time to allow blockchain to complete startup// we are listening to this event in the other file and this callback will initialize a new connection endCallback(); }, reconnectInterval); }); if (web3Instance == undefined) web3Instance = new web3(provider); else web3Instance.setProvider(provider); return web3Instance; } module.exports = { newBlockchainConnection }File app.。
本文来源:白菜网秒送体验金大全-www.acxtl.cn
返回