配置智能合约及使用Java编写后端接口
本次教程分为两部分,第一部分为智能合约的部署,第二部分为使用FISCO提供的Java SDK与链进行交互。
注意:每步操作请先看描述,按照步骤执行,然后与示意图对比,结果一样即为操作成功,结果不同请按步骤重试
智能合约部署
启动区块链
-
切换目录(注意,初始目录应为:~/)
cd fisco/
-
启动链
bash nodes/127.0.0.1/start_all.sh
启动WeBase
-
切换目录
cd webase-deploy/
-
启动WeBase
python3 deploy.py startDockerAll
部署智能合约
-
使用浏览器登录WeBase
-
添加私链用户
-
选择智能合约并部署
智能合约部署方式有多种,这里我们使用WeBase提供的可视化图形界面进行部署,此种方式较为方便简单,不易出错- 上传智能合约:这里我们使用Fisco提供的合约仓库中的Table.sol和TableTest.sol
现在,我们去到合约IDE中,就可以看到我们选择的智能合约了
注意:如果需要上传自己编写的合约,请使用合约IDE的上传功能,示例如下:
- 部署智能合约
先选择编译,在点击部署
- 上传智能合约:这里我们使用Fisco提供的合约仓库中的Table.sol和TableTest.sol
编写后端Java程序
这里,我们使用IDEA进行后端程序的编写 未安装IDEA的同学请先安装,并且请按照网上的教程配置一下Maven远程仓库
创建后端项目
注意JDK需要选择大于等于17的版本,没有的话需要下载
什么依赖项都不需要选择,直接点击创建
选择pom.xml,在dependencies标签中添加下面的依赖项:
1<dependency>
2 <groupId>org.springframework.boot</groupId>
3 <artifactId>spring-boot-starter-web</artifactId>
4 </dependency>
5 <dependency>
6 <groupId>org.springframework.boot</groupId>
7 <artifactId>spring-boot-starter-test</artifactId>
8 <scope>test</scope>
9 </dependency>
10 <dependency>
11 <groupId>org.fisco-bcos.java-sdk</groupId>
12 <artifactId>fisco-bcos-java-sdk</artifactId>
13 <version>2.9.1</version>
14 </dependency>
15 <dependency>
16 <groupId>org.projectlombok</groupId>
17 <artifactId>lombok</artifactId>
18 <version>1.18.32</version>
19 <scope>provided</scope>
20 </dependency>
在添加完成依赖项后,请点击右侧边栏的Maven标签,并点击刷新以加载依赖项
编写后端程序
- 新建三个文件夹(abi,bin,conf),位置如下图:
- 将合约的编译文件放分别放入对应的bin和abi文件夹,编译文件可在WeBase上下载: (在合约IDE中,选择侧边栏中的.sol文件,右键选择导出)
- 将下载的压缩包解压,将其中的abi和bin文件放到对应的文件夹:
- 在文件管理器中,打开Ubuntu中的SDK文件夹(具体路径如图)并将其中的文件导入conf文件夹中:
- 在resources文件夹中新建config.toml文件
文件内容如下:
1[cryptoMaterial]
2
3certPath = "conf" # The certification path
4
5# The following configurations take the certPath by default if commented
6# caCert = "conf/ca.crt" # CA cert file path
7# If connect to the GM node, default CA cert path is ${certPath}/gm/gmca.crt
8
9# sslCert = "conf/sdk.crt" # SSL cert file path
10# If connect to the GM node, the default SDK cert path is ${certPath}/gm/gmsdk.crt
11
12# sslKey = "conf/sdk.key" # SSL key file path
13# If connect to the GM node, the default SDK privateKey path is ${certPath}/gm/gmsdk.key
14
15# enSslCert = "conf/gm/gmensdk.crt" # GM encryption cert file path
16# default load the GM SSL encryption cert from ${certPath}/gm/gmensdk.crt
17
18# enSslKey = "conf/gm/gmensdk.key" # GM ssl cert file path
19# default load the GM SSL encryption privateKey from ${certPath}/gm/gmensdk.key
20
21[network]
22peers=["172.19.51.154:20200"] # The peer list to connect
23
24# AMOP configuration
25# You can use following two methods to configure as a private topic message sender or subscriber.
26# Usually, the public key and private key is generated by subscriber.
27# Message sender receive public key from topic subscriber then make configuration.
28# But, please do not config as both the message sender and the subscriber of one private topic, or you may send the message to yourself.
29
30# Configure a private topic as a topic message sender.
31# [[amop]]
32# topicName = "PrivateTopic"
33# publicKeys = [ "conf/amop/consumer_public_key_1.pem" ] # Public keys of the nodes that you want to send AMOP message of this topic to.
34
35# Configure a private topic as a topic subscriber.
36# [[amop]]
37# topicName = "PrivateTopic"
38# privateKey = "conf/amop/consumer_private_key.p12" # Your private key that used to subscriber verification.
39# password = "123456"
40
41
42[account]
43keyStoreDir = "account" # The directory to load/store the account file, default is "account"
44# accountFilePath = "" # The account file path (default load from the path specified by the keyStoreDir)
45accountFileFormat = "pem" # The storage format of account file (Default is "pem", "p12" as an option)
46
47# accountAddress = "" # The transactions sending account address
48# Default is a randomly generated account
49# The randomly generated account is stored in the path specified by the keyStoreDir
50
51# password = "" # The password used to load the account file
52
53[threadPool]
54channelProcessorThreadSize = "4" # The size of the thread pool to process channel callback
55# Default is the number of cpu cores
56
57receiptProcessorThreadSize = "4" # The size of the thread pool to process transaction receipt notification
58# Default is the number of cpu cores
59
60maxBlockingQueueSize = "102400" # The max blocking queue size of the thread pool
- 打开FiscoApplicationTests.Java文件,添加以下内容:
1package com.example.fisco;
2
3import org.fisco.bcos.sdk.BcosSDK;
4import org.fisco.bcos.sdk.abi.ABICodecException;
5import org.fisco.bcos.sdk.client.Client;
6import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair;
7import org.fisco.bcos.sdk.transaction.manager.AssembleTransactionProcessor;
8import org.fisco.bcos.sdk.transaction.manager.TransactionProcessorFactory;
9import org.fisco.bcos.sdk.transaction.model.dto.TransactionResponse;
10import org.fisco.bcos.sdk.transaction.model.exception.TransactionBaseException;
11import org.junit.jupiter.api.BeforeAll;
12import org.junit.jupiter.api.Test;
13import org.springframework.boot.test.context.SpringBootTest;
14
15import java.util.ArrayList;
16import java.util.List;
17
18@SpringBootTest
19class FiscoApplicationTests {
20static final String *configFile* ="src/main/resources/config.toml";
21static final String *address*="";//合约地址 需要到WeBase中查看合约编译后的具体地址
22static BcosSDK *sdk*;
23static Client *client*;
24static AssembleTransactionProcessor *transactionProcessor*;
25@BeforeAll
26static void setUpBeforeClass() throws Exception {
27*sdk*=BcosSDK.*build*(*configFile*);
28*client*=*sdk*.getClient(1);
29CryptoKeyPair keyPair = client.getCryptoSuite().createKeyPair();
30*transactionProcessor* = TransactionProcessorFactory.*createAssembleTransactionProcessor*(client,keyPair,"src/main/resources/abi/", "src/main/resources/bin/");
31}
32
33@Test
34void contextLoads() throws ABICodecException, TransactionBaseException {
35List\<Object\> params=new ArrayList\<\>();
36String MethodName=""; //需要调用的合约中某一个方法的名称
37params.add("");//方法需要携带的参数
38params.add("");
39params.add("");
40TransactionResponse response = *transactionProcessor*.sendTransactionAndGetResponseByContractLoader("TableTest", *address*, MethodName, params);
41System.*out*.println(response);
42}
43
44}
其中address需要到WeBase中查看,然后填写到address中:
还有MethodName和Params参数需要填写,具体内容取决于你的合约中的函数名称以及函数参数(点击发交易可以看到具体的内容)
- 运行后端程序,并在WeBase中查看结果:
可以看到,交易回执已经成功打印出来了
因为使用insert方法插入了一条记录,我们可以在WeBase中使用发交易中的select方法来查看刚刚插入的记录(它需要一个参数作为查询的依据):
可以看到,数据已经成功的插入到了区块链中
到此,基础的后端程序与Fisco区块链的交互就已经完成了
更多的内容可以查阅官方的JavaSDK文档,还有很多不同功能的方法可以选择:
Java SDK — FISCO BCOS 2.0 v2.9.0 文档 (fisco-bcos-documentation.readthedocs.io)
区块链功能接口列表 — FISCO BCOS 2.0 v2.9.0 文档 (fisco-bcos-documentation.readthedocs.io)
标题:在Windows上运行Fisco区块链的第三步——配置智能合约及使用Java编写后端接口
作者:flying
地址:https://flyingcoding.cn/articles/2024/09/01/1725182806114.html