Fisco Bcos学习 - JavaSDK使用

一、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.crtsdk.crtsdk.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对象的getBlockNumbergetBlockByNumber等方法实现。

五、常见问题与解决方案

5.1 连接异常

若出现Handshake failed等连接错误,可能是证书配置问题:

  • 确保ca.crtsdk.crtsdk.key路径正确
  • 检查节点证书与SDK证书是否匹配
  • 确认网络能正常访问节点的channel端口

5.2 合约调用失败

合约调用返回错误时:

  • 检查Gas参数是否足够,适当增加GasLimit
  • 确认合约方法签名和参数类型正确
  • 通过节点日志查看交易执行的详细错误信息

更多详细内容参考:https://www.bookstack.cn/read/fisco-bcos-2.4-zh/1f3379606a334936.md

### 设置和执行 FISCO-BCOS Java SDK 环境测试 #### 准备工作 为了准备FISCO-BCOS Java SDK的环境测试,需要先确保项目结构合理,并导入必要的依赖项。对于Gradle构建工具而言,在`build.gradle`文件中的dependencies部分应加入特定版本的fisco-bcos-java-sdk库[^2]。 ```groovy dependencies { compile (&#39;org.fisco-bcos.java-sdk:fisco-bcos-java-sdk:2.7.2&#39;) { exclude group: &#39;org.slf4j&#39; } } ``` #### 配置文件说明 涉及到了几个重要的配置类:`BCosSDKConfig`, `ClientConfig`, 和 `ContractConfig`。这些配置按照一定的逻辑顺序排列来初始化客户端连接以及合约交互所需的信息[^4]。 #### 创建示例合约 创建名为`HelloWorld`的智能合约作为例子,其对应的Java接口位于`java-sdk-demo/src/main/java/org/fisco/bcos/sdk/demo/contract/HelloWorld.java`下;而Solidity源码则存放在同一目录内的`sol`子文件夹中[^3]。 #### 编写性能测试代码 编写专门用于评估系统表现力的应用程序,比如命名为`PerformanceHelloWorld.java`,该应用能够模拟大量请求并发访问部署于链上的服务实例,从而帮助开发者了解实际运行状况下的效率与稳定性。 #### 执行测试前验证 在正式开展任何类型的负载试验之前,建议先行完成基本的功能性检测,确认所有组件均能正常协作无误之后再逐步增加复杂度至全面的压力评测阶段。 #### 测试证书管理 涉及到安全通信方面,则需妥善处理好认证材料如CA根证书(`ca.crt`)、节点公钥证书(`sdk.crt`)及私钥(`sdk.key`)等资源的位置放置问题,通常是从指定路径复制到目标环境中去使用[^5]。 ```bash cp -rf ../nodes/127.0.0.1//sdk/* ./ ``` 通过上述步骤可建立起一套完整的基于FISCO BCOS平台之上采用Java语言实现的服务端应用程序框架,并为进一步深入研究提供了坚实的基础支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

来自马达加斯加的黑猫杰克

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值