本实例主要是将企业信息添加进区块链,然后实现对企业信息进行查询溯源,对区块链有新增、查询、修改、删除、查看历史等功能。

1、准备一个bsn-springboot项目

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.yuyun</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot</name>
    <description>springboot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2、引入jar包

 

项目下新建一个lib目录,将jar包放入

springboot如何从区块链获取数据 springboot区块链框架_java

然后再pom.xml文件引入该jar包

<dependency>
    <groupId>com.example.javacc</groupId>
    <artifactId>bsn-sdk-java</artifactId>
    <version>1.0-SNAPSHOT</version>
    <scope>system</scope>
    <systemPath>${pom.basedir}/lib/bsn-sdk-java-jar-with-dependencies.jar</systemPath>
</dependency>

3、区块链配置

方法一:新建config.json文件

在resources目录下新建个config目录,再在其中新建config.json文件,格式如下:

{
  "userPrivateKey": "",
  "bsnPublicKey": "",
  "appCode": "",
  "userCode": "",
  "nodeApi": "",
  "mspPath": ""
}

其中的内容,打开区块链官网我参与的服务

springboot如何从区块链获取数据 springboot区块链框架_spring_02

点击下载秘钥,下载解压后的文件,userAppCert目录中的两个文件,一个是私钥,一个是公钥,分别对应config.json中的userPrivateKey和bsnPublicKey

springboot如何从区块链获取数据 springboot区块链框架_区块链_03

将两个文件里面的所有内容复制了放入,例如:

{
  "userPrivateKey": "-----BEGIN PRIVATE KEY-----\nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgVbS8svrC3sdFgIFW\nUoLfczfjCjq0z7fGTSFfqMkjssChRANCAARXn4a1tA3PB8+wx9UgU0GDfGBG7BXZ\nENL5GN3vYXqpcbCtvxAtINSK02KcQ1a6jAASy79T0ax9KfQDjzGVFN9K\n-----END PRIVATE KEY-----",
  "bsnPublicKey": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV5+GtbQNzwfPsMfVIFNBg3xgRuwV\n2RDS+Rjd72F6qXGwrb8QLSDUitNinENWuowAEsu/U9GsfSn0A48xlRTfSg==\n-----END PUBLIC KEY-----",
  "appCode": "app008809d6356825a4c249be16572723c6225",
  "userCode": "USER0001202112061433104102226",
  "nodeApi": "http://52.83.209.158:17502",
  "mspPath": ""
}

方法二:直接将userAppCert目录中的两个文件放进resources目录下

springboot如何从区块链获取数据 springboot区块链框架_java_04

4、初始化config方法

如果区块链配置采用方法一,初始化config的代码如下:

public void initConfig() {
    String filePath = "config/config.json";
    Config config = Config.buildByConfigJson(filePath);
    config.initConfig(config);
}

如果采用方法二,初始化config的代码如下:

public void initConfig() throws IOException {
    Config config = new Config();
    config.setAppCode("app008809d6356825a4c249be16572723c6225");
    config.setUserCode("USER0001202112061433104102226");
    config.setApi("http://52.83.209.158:17502");
    config.setPrk(Common.readFile("cert/private_key.pem"));
    config.setPuk(Common.readFile("cert/public_key.pem"));
    config.setMspDir("");
    config.initConfig(config);
}

本实例采用方法一

5、具体实现

新建一个Service层代码,具体如下:

package com.yuyun.service;

import com.yuyun.dto.BsnHistoryDTO;
import com.yuyun.dto.CompanyDTO;

import java.io.IOException;
import java.util.List;

/**
 * @author hyh
 */
public interface FabricBsnService {

    /**
     * 保存(添加or修改)
     *
     * @param key  键值
     * @param body 内容
     * @return 成功 true
     * @return Boolean
     */
    Boolean save(String key, String body);

    /**
     * 查询
     *
     * @param key 键值
     * @return 结果
     */
    CompanyDTO query(String key);

    /**
     * 历史查询
     *
     * @param key 键值
     * @return 解密后的结果
     * @throws IOException 异常
     */
    List<BsnHistoryDTO> getHistory(String key) throws IOException;

    /**
     * 删除
     *
     * @param key 键值
     * @return 成功 true
     * @return Boolean
     */
    Boolean delete(String key);
}

新建Service类的实现

package com.yuyun.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bsnbase.sdk.client.fabric.FabricClient;
import com.bsnbase.sdk.entity.config.Config;
import com.bsnbase.sdk.entity.req.fabric.ReqKeyEscrow;
import com.bsnbase.sdk.entity.res.fabric.ResKeyEscrow;
import com.yuyun.dto.BsnHistoryDTO;
import com.yuyun.dto.CompanyDTO;
import com.yuyun.service.FabricBsnService;
import com.yuyun.utils.Base64Utils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author hyh
 */
@Log4j2
@Service
public class FabricBsnServiceImpl implements FabricBsnService {

    /**
     * 初始化config
     */
    public void initConfig() {
        String filePath = "config/config.json";
        Config config = Config.buildByConfigJson(filePath);
        config.initConfig(config);
    }

    public String reqChainCode(String key, String funcName, String body) {
        try {
            initConfig();
            ReqKeyEscrow keyEscrow = new ReqKeyEscrow();

            String[] args;
            if (StringUtils.isNotBlank(body)) {
                args = new String[]{key, body};
            } else {
                args = new String[]{key};
            }

            keyEscrow.setArgs(args);
            keyEscrow.setFuncName(funcName);
            //链码部署名称,在我参与的服务信息中可以找到
            keyEscrow.setChainCode("cc_app0001");

            keyEscrow.setTransientData(new HashMap<>());
            ResKeyEscrow resKeyEscrow = FabricClient.reqChainCode(keyEscrow);
            if (200 == resKeyEscrow.getCcRes().getCcCode()) {
                String str = resKeyEscrow.getCcRes().getCcData();
                if ("null".equals(str)) {
                    return null;
                }
                return str;
            }
        } catch (Exception e) {
            throw new RuntimeException("区块链访问失败:" + e.getMessage());
        }
        return null;
    }

    @Override
    public Boolean save(String key, String body) {
        log.info("key:" + key);
        String s = reqChainCode(key, "Set", body);
        return StringUtils.isNotBlank(s);
    }

    @Override
    public CompanyDTO query(String key) {
        String queryStr = reqChainCode(key, "Query", null);
        if (StringUtils.isBlank(queryStr)) {
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(queryStr);

        return jsonObject.toJavaObject(CompanyDTO.class);
    }

    @Override
    public List<BsnHistoryDTO> getHistory(String key) throws IOException {
        String historyStr = reqChainCode(key, "History", null);
        if (StringUtils.isBlank(historyStr)) {
            return new ArrayList<>();
        }
        JSONArray jsonArray = JSONArray.parseArray(historyStr);

        List<BsnHistoryDTO> bsnHistoryDTOList = jsonArray.toJavaList(BsnHistoryDTO.class);
        for (BsnHistoryDTO b : bsnHistoryDTOList) {
            if (null != b) {
                String value = Base64Utils.Base64Decode(b.getValue().getBytes());
                if (StringUtils.isNotBlank(value)) {
                    JSONObject jsonObject = JSONObject.parseObject(value);
                    CompanyDTO companyDTO = jsonObject.toJavaObject(CompanyDTO.class);
                    b.setCompanyDTO(companyDTO);
                }
                b.setValue("");
            }
        }

        return bsnHistoryDTOList;
    }

    @Override
    public Boolean delete(String key) {
        String s = reqChainCode(key, "Delete", null);
        return "success".equals(s);
    }
}

新建Controller层

package com.yuyun.controller;

import com.yuyun.dto.BsnHistoryDTO;
import com.yuyun.dto.CompanyDTO;
import com.yuyun.service.FabricBsnService;
import com.yuyun.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * @author hyh
 */
@RestController
@RequestMapping("fabricBsn")
@Api(tags = "区块链")
public class FabricBsnController {

    @Autowired
    private FabricBsnService fabricBsnService;

    @GetMapping("history/{key}")
    @ApiOperation("历史记录")
    public Result<List<BsnHistoryDTO>> history(@PathVariable("key") String key) throws IOException {
        List<BsnHistoryDTO> bsnHistoryDTOList = fabricBsnService.getHistory(key);

        return new Result<List<BsnHistoryDTO>>().success(bsnHistoryDTOList);
    }

    @GetMapping("query/{key}")
    @ApiOperation("信息")
    public Result<CompanyDTO> get(@PathVariable("key") String key) {

        CompanyDTO data = fabricBsnService.query(key);

        return new Result<CompanyDTO>().success(data);
    }

    @DeleteMapping("{key}")
    @ApiOperation("删除")
    public Result<Object> delete(@PathVariable("key") String key) {

        return new Result<>().ok(fabricBsnService.delete(key));
    }
}

在企业管理中调用区块链的方法

先引入,再调用

@Autowiredprivate FabricBsnService fabricBsnService;
  • 新增信息
fabricBsnService.save("company_" + companyDTO.getId(), JSON.toJSONString(companyDTO));
  • 修改信息
fabricBsnService.save("company_" + companyDTO.getId(), JSON.toJSONString(companyDTO));
  • 删除信息
fabricBsnService.delete("company_" + id);

6、运行效果

(1)添加企业信息

springboot如何从区块链获取数据 springboot区块链框架_区块链_05

(2)查看企业信息

springboot如何从区块链获取数据 springboot区块链框架_json_06

(3)查看区块链信息

springboot如何从区块链获取数据 springboot区块链框架_spring boot_07

(4)修改企业信息

springboot如何从区块链获取数据 springboot区块链框架_区块链_08

(5)再次查看区块链信息

springboot如何从区块链获取数据 springboot区块链框架_spring_09

(6)删除企业信息

springboot如何从区块链获取数据 springboot区块链框架_json_10

(7)第三次查看区块链信息

可以看到信息已经被删除了

springboot如何从区块链获取数据 springboot区块链框架_区块链_11

(8)查看区块链历史记录

springboot如何从区块链获取数据 springboot区块链框架_区块链_12

返回结果如下,所有的信息历史都在里面

{
  "code": 0,
  "msg": "success",
  "data": [
    {
      "key": "company_1473572863141011458",
      "txId": "55dab6883d0f0d29b45175a5d98b3816b24be39af35f5fb012b165019769db23",
      "isDelete": "true",
      "time": "2021-12-22T00:42:03.498+00:00",
      "value": "",
      "companyDTO": null
    },
    {
      "key": "company_1473572863141011458",
      "txId": "9b8a0509eb37546cec7e50d0f854eea8030caf67904221b695bba0ea00742396",
      "isDelete": "false",
      "time": "2021-12-22T00:40:21.797+00:00",
      "value": "",
      "companyDTO": {
        "id": 1473572863141011458,
        "companyName": "企业名称1",
        "description": "企业描述2",
        "businessLicense": "测试营业执照3",
        "address": "测试地址4",
        "status": null,
        "remarks": "备注5",
        "createDate": null,
        "updateDate": null
      }
    },
    {
      "key": "company_1473572863141011458",
      "txId": "c1deb5b1911509347878d67af6c1e28b45ac37a1916f0d4c32e917d937a5b1a8",
      "isDelete": "false",
      "time": "2021-12-22T00:35:25.207+00:00",
      "value": "",
      "companyDTO": {
        "id": 1473572863141011458,
        "companyName": "企业名称",
        "description": "企业描述",
        "businessLicense": "测试营业执照",
        "address": "测试地址",
        "status": null,
        "remarks": "备注",
        "createDate": null,
        "updateDate": null
      }
    }
  ]
}