文章目录
一、JavaSDK简介
FISCO BCOS的Java SDK(Web3SDK)是用于与FISCO BCOS区块链网络进行交互的Java开发工具包,提供了丰富的API,支持访问节点、查询状态、发送交易、部署和调用智能合约等功能。本文将详细介绍JavaSDK的基本使用方法,帮助开发者快速上手。
二、环境准备
2.1 环境要求
- Java版本:JDK 1.8或以上版本,推荐使用Oracle JDK(CentOS的OpenJDK可能缺少JCE,导致连接问题)
- 区块链环境:已搭建的FISCO BCOS 2.0+区块链网络
- 网络连通性:确保SDK所在环境能访问节点的channel端口(默认20200开始)
2.2 引入依赖
通过Maven引入SDK依赖:
<dependency>
<groupId>org.fisco.bcos</groupId>
<artifactId>web3sdk</artifactId>
<version>2.1.0</version>
</dependency>
如果使用Gradle:
compile 'org.fisco.bcos:web3sdk:2.1.0'
2.3 仓库配置
由于引入了以太坊相关依赖,需要在项目中添加以太坊的Maven仓库:
repositories {
mavenCentral()
maven { url "https://dl.bintray.com/ethereum/maven/" }
}
三、配置SDK
3.1 证书准备
FISCO BCOS作为联盟链,SDK连接节点需要通过证书进行双向认证。需要将节点目录下的ca.crt
、sdk.crt
和sdk.key
文件拷贝到项目的资源目录(如src/main/resources
)。
3.2 Spring项目配置
在Spring项目中,通过applicationContext.xml
配置SDK:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="encryptType" class="org.fisco.bcos.web3j.crypto.EncryptType">
<constructor-arg value="0"/> <!-- 0:标准模式 1:国密模式 -->
</bean>
<bean id="groupChannelConnectionsConfig" class="org.fisco.bcos.channel.handler.GroupChannelConnectionsConfig">
<property name="caCert" value="ca.crt" />
<property name="sslCert" value="sdk.crt" />
<property name="sslKey" value="sdk.key" />
<property name="allChannelConnections">
<list>
<bean id="group1" class="org.fisco.bcos.channel.handler.ChannelConnections">
<property name="groupId" value="1" />
<property name="connectionsStr">
<list>
<value>127.0.0.1:20200</value>
<value>127.0.0.1:20201</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
<bean id="channelService" class="org.fisco.bcos.channel.client.Service" depends-on="groupChannelConnectionsConfig">
<property name="groupId" value="1" />
<property name="agencyName" value="fisco" />
<property name="allChannelConnections" ref="groupChannelConnectionsConfig"></property>
</bean>
</beans
四、核心功能使用示例
4.1 初始化Web3j实例
在Spring配置的基础上,通过ChannelEthereumService
获取Web3j
实例,用于后续操作:
import org.fisco.bcos.channel.client.Service;
import org.fisco.bcos.web3j.protocol.Web3j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Service channelService = context.getBean(Service.class);
Web3j web3j = channelService.getWeb3j();
try {
// 检查是否成功连接节点
System.out.println(web3j.getBlockNumber().send().getBlockNumber());
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述代码通过加载Spring配置文件,获取Service
实例进而得到Web3j
对象,并尝试获取当前区块链的区块高度,验证连接是否成功。
4.2 部署智能合约
JavaSDK提供了便捷的合约部署接口,以部署简单的HelloWorld
合约为例:
import org.fisco.bcos.web3j.abi.datatypes.Address;
import org.fisco.bcos.web3j.abi.datatypes.Uint;
import org.fisco.bcos.web3j.crypto.Credentials;
import org.fisco.bcos.web3j.crypto.Keys;
import org.fisco.bcos.web3j.protocol.Web3j;
import org.fisco.bcos.web3j.tx.gas.StaticGasProvider;
import org.fisco.bcos.web3j.utils.Numeric;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.math.BigInteger;
public class DeployContract {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Service channelService = context.getBean(Service.class);
Web3j web3j = channelService.getWeb3j();
// 从私钥创建Credentials对象
String privateKey = "0x..."; // 替换为实际私钥
Credentials credentials = Credentials.create(privateKey);
// 设置Gas相关参数
BigInteger gasPrice = BigInteger.valueOf(30000000);
BigInteger gasLimit = BigInteger.valueOf(3000000);
StaticGasProvider gasProvider = new StaticGasProvider(gasPrice, gasLimit);
try {
// 部署合约
HelloWorld helloWorld = HelloWorld.deploy(web3j, credentials, gasProvider).send();
System.out.println("Contract deployed at: " + helloWorld.getContractAddress());
} catch (Exception e) {
e.printStackTrace();
}
}
}
其中,HelloWorld
合约是通过Solidity编写并使用合约编译工具生成的Java合约类,部署过程指定了签名凭证、Gas价格和Gas限制等参数。
4.3 调用智能合约
合约部署完成后,可通过JavaSDK调用合约方法:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class CallContract {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Service channelService = context.getBean(Service.class);
Web3j web3j = channelService.getWeb3j();
String contractAddress = "0x..."; // 替换为实际合约地址
String privateKey = "0x..."; // 替换为实际私钥
Credentials credentials = Credentials.create(privateKey);
try {
HelloWorld helloWorld = HelloWorld.load(contractAddress, web3j, credentials, new StaticGasProvider(
BigInteger.valueOf(30000000), BigInteger.valueOf(3000000)));
// 调用合约方法
String result = helloWorld.sayHello().send();
System.out.println("Result: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述代码通过load
方法加载已部署的合约实例,然后调用sayHello
方法获取合约返回结果 。
4.4 查询区块链状态
除合约操作外,JavaSDK还支持查询区块链的各种状态信息:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class QueryBlockchain {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Service channelService = context.getBean(Service.class);
Web3j web3j = channelService.getWeb3j();
try {
// 获取当前区块高度
BigInteger blockNumber = web3j.getBlockNumber().send().getBlockNumber();
System.out.println("Current block number: " + blockNumber);
// 获取最新区块信息
org.fisco.bcos.web3j.protocol.core.methods.response.EthBlock.Block block =
web3j.getBlockByNumber(Numeric.toBigInt(blockNumber), true).send().getBlock();
System.out.println("Block hash: " + block.getHash());
} catch (Exception e) {
e.printStackTrace();
}
}
}
该示例展示了获取当前区块高度和最新区块详细信息的方法,通过web3j
对象的getBlockNumber
和getBlockByNumber
等方法实现。
五、常见问题与解决方案
5.1 连接异常
若出现Handshake failed
等连接错误,可能是证书配置问题:
- 确保
ca.crt
、sdk.crt
和sdk.key
路径正确 - 检查节点证书与SDK证书是否匹配
- 确认网络能正常访问节点的channel端口
5.2 合约调用失败
合约调用返回错误时:
- 检查Gas参数是否足够,适当增加GasLimit
- 确认合约方法签名和参数类型正确
- 通过节点日志查看交易执行的详细错误信息
更多详细内容参考:https://www.bookstack.cn/read/fisco-bcos-2.4-zh/1f3379606a334936.md