- java环境配置
- 基础概念
- java环境搭建
- maven包引用
- java代码
- Ganache
- 执行结果
- 代码解释
可以不让搞,但是不允许你不会
java环境配置- jdk版本,jdk1.8+;
- IDE环境,ideas;
- 依赖包,web3;
- 区块链网路,开发网,Ganache;
区块链网络: 提供区块链交易的网络,测试网和正式网由以太坊提供,开发网络可以本地安装,ganache,Hardhat是两个可以本地安装的区块链服务器,ganache是本教程使用的开发区块链服务器。
web3:与区块链进行交互的网络协议,web3目前有python,nodejs,java,typescript等语言实现
gas:交易手续费,就是我们所说的(挖矿)费,区块链上的所有操作都由网络带宽存储的成本,这部分费用需要由交易方提供
jdk1.8
ideas创建java项目引导
file—>New—>Project
ideas创建java项目,命名 ethJavaLession01
java代码org.web3j core 5.0.0 org.apache.commons commons-lang3 3.12.0 central central https://maven.aliyun.com/repository/central true false jcenter jcenter http://jcenter.bintray.com/ true false maven-net-cn Maven China Mirror https://dl.bintray.com/ethereum/maven true false
package com.eth;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.EthBlockNumber;
import org.web3j.protocol.core.methods.response.EthGasPrice;
import org.web3j.protocol.core.methods.response.Web3ClientVersion;
import org.web3j.protocol.http.HttpService;
import java.io.IOException;
public class EthTest {
public static void main(String[] args) {
System.out.println("Connecting to Ethereum ...");
Web3j web3 = Web3j.build(new HttpService("HTTP://127.0.0.1:7545"));
System.out.println("Successfuly connected to Ethereum");
try {
// web3_clientVersion returns the current client version.
Web3ClientVersion clientVersion = web3.web3ClientVersion().send();
// eth_blockNumber returns the number of most recent block.
EthBlockNumber blockNumber = web3.ethBlockNumber().send();
// eth_gasPrice, returns the current price per gas in wei.
EthGasPrice gasPrice = web3.ethGasPrice().send();
// Print result
System.out.println("Client version: " + clientVersion.getWeb3ClientVersion());
System.out.println("Block number: " + blockNumber.getBlockNumber());
System.out.println("Gas price: " + gasPrice.getGasPrice());
} catch (IOException ex) {
throw new RuntimeException("Error whilst sending json-rpc requests", ex);
}
}
}
Ganache
Ganache为可以本地启动的开发区块链服务器
ganache官网地址
Successfuly connected to Ethereum
Client version: EthereumJS TestRPC/v2.13.1/ethereum-js
Block number: 0
Gas price: 20000000000
Web3j web3 = Web3j.build(new HttpService(“HTTP://127.0.0.1:7545”))
连接区块链服务器
Web3ClientVersion clientVersion = web3.web3ClientVersion().send();
客户端版本号
EthBlockNumber blockNumber = web3.ethBlockNumber().send();
获取当前区块链中块个数
EthGasPrice gasPrice = web3.ethGasPrice().send();
获取gas值



