SpringBoot区块链之以太坊区块高度扫描(简洁版)
来源:互联网
持续昨天的demo往下写写:[SpringBoot区块链之以太坊开发(整合Web3j)](https://juejin.im/post/5d88e6c1518825094f69e887),将庞杂的逻辑都去除,留下最简略区块高度扫描部份代码,这样更好让开发者上手
首先自定义个区块高度处置线程类
```
package com.xiaobin.ethdemo.component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.EthBlockNumber;
/**
* 创立时光: 2019/9/24 23:08
* 备注:
* 码农自学交换小群:260532022,欢迎大家的参加,分享学习是一件开心事
**/
@Component
public class EthWatcher implements Runnable {
@Autowired
private Web3j web3j;
// 是不是停滞扫描
private boolean stop = false;
// 当前区块高度
private Long currentBlockHeight = 8612532L;
// 期待扫描事件
private Long checkInterval = 5000L;
//区块确认数
private int confirmation = 1;
// 每次扫描区块的数目
private int step = 5;
public void check() {
try {
Long networkBlockNumber = getNetworkBlockHeight() - confirmation + 1;
System.out.println(networkBlockNumber);
currentBlockHeight = (networkBlockNumber - currentBlockHeight > step) ? currentBlockHeight + step : networkBlockNumber;
System.out.println("扫描当前区块高度:"+currentBlockHeight);
System.out.println("当前网络区块高度:"+networkBlockNumber);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
stop = false;
long nextCheck = 0;
while (!(Thread.interrupted() || stop)) {
if (nextCheck test() throws Exception{
List持续昨天的demo往下写写:[SpringBoot区块链之以太坊开发(整合Web3j)](https