Spring Boot整合区块链—区块链服务开发实例

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

1、准备一个bsn-springboot项目

pom.xml


<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.6.1version>
        <relativePath/> 
    parent>

    <groupId>com.yuyungroupId>
    <artifactId>springbootartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>springbootname>
    <description>springbootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>
project>

2、引入jar包

下载: https://yuyunyaohui.lanzoul.com/iwnMXxuxm2f 密码:hk9i

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

Spring Boot整合区块链—区块链服务开发实例_第1张图片

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

<dependency>
    <groupId>com.example.javaccgroupId>
    <artifactId>bsn-sdk-javaartifactId>
    <version>1.0-SNAPSHOTversion>
    <scope>systemscope>
    <systemPath>${pom.basedir}/lib/bsn-sdk-java-jar-with-dependencies.jarsystemPath>
dependency>

3、区块链配置

方法一:新建config.json文件

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

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

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

Spring Boot整合区块链—区块链服务开发实例_第2张图片

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

Spring Boot整合区块链—区块链服务开发实例_第3张图片

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

{
  "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目录下

Spring Boot整合区块链—区块链服务开发实例_第4张图片

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)添加企业信息

Spring Boot整合区块链—区块链服务开发实例_第5张图片

(2)查看企业信息

Spring Boot整合区块链—区块链服务开发实例_第6张图片

(3)查看区块链信息

Spring Boot整合区块链—区块链服务开发实例_第7张图片

(4)修改企业信息

Spring Boot整合区块链—区块链服务开发实例_第8张图片

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

Spring Boot整合区块链—区块链服务开发实例_第9张图片

(6)删除企业信息

Spring Boot整合区块链—区块链服务开发实例_第10张图片

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

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

Spring Boot整合区块链—区块链服务开发实例_第11张图片

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

Spring Boot整合区块链—区块链服务开发实例_第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
      }
    }
  ]
}

demo:https://gitee.com/hyh17808770899/spring-boot/tree/master/springboot-bsn

你可能感兴趣的:(区块链,Spring,Boot,区块链,java,spring,boot)