本实例主要是将企业信息添加进区块链,然后实现对企业信息进行查询溯源,对区块链有新增、查询、修改、删除、查看历史等功能。
1、准备一个bsn-springboot项目pom.xml
2、引入jar包4.0.0 org.springframework.boot spring-boot-starter-parent2.6.1 com.yuyun springboot0.0.1-SNAPSHOT springboot springboot 1.8 org.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-testtest org.springframework.boot spring-boot-maven-plugin
下载: https://yuyunyaohui.lanzoul.com/iwnMXxuxm2f 密码:hk9i
项目下新建一个lib目录,将jar包放入
然后再pom.xml文件引入该jar包
3、区块链配置 方法一:新建config.json文件com.example.javacc bsn-sdk-java1.0-SNAPSHOT system ${pom.basedir}/lib/bsn-sdk-java-jar-with-dependencies.jar
在resources目录下新建个config目录,再在其中新建config.json文件,格式如下:
{ "userPrivateKey": "", "bsnPublicKey": "", "appCode": "", "userCode": "", "nodeApi": "", "mspPath": "" }
其中的内容,打开区块链官网我参与的服务
点击下载秘钥,下载解压后的文件,userAppCert目录中的两个文件,一个是私钥,一个是公钥,分别对应config.json中的userPrivateKey和bsnPublicKey
将两个文件里面的所有内容复制了放入,例如:
{ "userPrivateKey": "-----BEGIN PRIVATE KEY-----nMIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgVbS8svrC3sdFgIFWnUoLfczfjCjq0z7fGTSFfqMkjssChRANCAARXn4a1tA3PB8+wx9UgU0GDfGBG7BXZnENL5GN3vYXqpcbCtvxAtINSK02KcQ1a6jAASy79T0ax9KfQDjzGVFN9Kn-----END PRIVATE KEY-----", "bsnPublicKey": "-----BEGIN PUBLIC KEY-----nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV5+GtbQNzwfPsMfVIFNBg3xgRuwVn2RDS+Rjd72F6qXGwrb8QLSDUitNinENWuowAEsu/U9GsfSn0A48xlRTfSg==n-----END PUBLIC KEY-----", "appCode": "app008809d6356825a4c249be16572723c6225", "userCode": "USER0001202112061433104102226", "nodeApi": "http://52.83.209.158:17502", "mspPath": "" }方法二:直接将userAppCert目录中的两个文件放进resources目录下 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; public interface FabricBsnService { Boolean save(String key, String body); CompanyDTO query(String key); ListgetHistory(String key) throws IOException; 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; @Log4j2 @Service public class FabricBsnServiceImpl implements FabricBsnService { 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 ListgetHistory(String key) throws IOException { String historyStr = reqChainCode(key, "History", null); if (StringUtils.isBlank(historyStr)) { return new ArrayList<>(); } JSONArray jsonArray = JSONArray.parseArray(historyStr); List 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; @RestController @RequestMapping("fabricBsn") @Api(tags = "区块链") public class FabricBsnController { @Autowired private FabricBsnService fabricBsnService; @GetMapping("history/{key}") @ApiOperation("历史记录") public Result> history(@PathVariable("key") String key) throws IOException { List
bsnHistoryDTOList = fabricBsnService.getHistory(key); return new Result >().success(bsnHistoryDTOList); } @GetMapping("query/{key}") @ApiOperation("信息") public Result
get(@PathVariable("key") String key) { CompanyDTO data = fabricBsnService.query(key); return new Result ().success(data); } @DeleteMapping("{key}") @ApiOperation("删除") public Result
在企业管理中调用区块链的方法
先引入,再调用
@Autowiredprivate FabricBsnService fabricBsnService;
-
新增信息
fabricBsnService.save("company_" + companyDTO.getId(), JSON.toJSONString(companyDTO));
-
修改信息
fabricBsnService.save("company_" + companyDTO.getId(), JSON.toJSONString(companyDTO));
-
删除信息
fabricBsnService.delete("company_" + id);
可以看到信息已经被删除了
(8)查看区块链历史记录返回结果如下,所有的信息历史都在里面
{ "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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)