当前位置: 首页 > news >正文

数据对接 模板设计模式的使用

与上游系统常有数据对接的需求,对接的接口在入参 返回值 数据处理逻辑上常有一定的规律性,使用模板方法 可以减少样本代码 提高代码效率
这里给出一个示例

同步上游系统的账号 组织(业务方请求接口)

抽象类

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;@Slf4j
public abstract class AbstractSync<T,K extends ServiceImpl<? extends BaseMapper<T>,T>> {@Value("${xxx}")private String appId;@Value("${xxx}")private String appSecret;abstract protected void sync();abstract protected String getReqUrl();abstract protected String getCallbackUrl();abstract protected String getReqFailedMsg();abstract protected String getCallbackFailedMsg();abstract protected Class<T> entityClass();abstract protected K getBaseService();abstract protected Function<T,Date> sortFunc();abstract protected SFunction<T,String> bizIdFunc();abstract protected Function<T,String> callbackIdFunc();public void doSync() {JSONArray dataJsonArray = new JSONArray();this.getReqData(dataJsonArray,1,100,LocalDateTime.now().plusMinutes(-30).toInstant(ZoneOffset.ofHours(8)).toEpochMilli());List<T> tList = dataJsonArray.toJavaList(this.entityClass());tList.sort(Comparator.comparing(this.sortFunc()));K baseService = this.getBaseService();tList.forEach(t -> {T existedT = baseService.lambdaQuery().eq(this.bizIdFunc(), this.bizIdFunc().apply(t)).one();if(Objects.nonNull(existedT)){baseService.lambdaUpdate().eq(this.bizIdFunc(),this.bizIdFunc().apply(t)).update(t);}else{baseService.save(t);}});this.callback(tList,this.callbackIdFunc());}public void callback(List<T> tList, Function<T,String> func){if(CollectionUtil.isNotEmpty(tList)){String ids = tList.stream().map(func).collect(Collectors.joining(","));JSONObject reqParamsJson = new JSONObject();reqParamsJson.put("ids",ids);String response = this.doReq(reqParamsJson,this.getCallbackUrl());String code = JSONObject.parseObject(response).getString("code");if(!"0".equals(code)){throw new RuntimeException(this.getCallbackFailedMsg());}}}public JSONArray getReqData(JSONArray dataJsonArray, Integer page, Integer pageSize, Long startTime){String response = this.request(page,pageSize,startTime);JSONObject resultJson = JSONObject.parseObject(response);JSONObject dataJson = resultJson.getJSONObject("data");String code = resultJson.getString("code");JSONArray data = dataJson.getJSONArray("list");if(!"0".equals(code)){throw new RuntimeException(this.getReqFailedMsg());}if(!data.isEmpty()){dataJsonArray.addAll(data);}if(data.size() >= pageSize){getReqData(dataJsonArray,++page,pageSize,startTime);}return dataJsonArray;}public String request(Integer page,Integer size,Long startTime){JSONObject reqParamsJson = new JSONObject();reqParamsJson.put("page",page.toString());reqParamsJson.put("size",size.toString());reqParamsJson.put("startTime",startTime.toString());return this.doReq(reqParamsJson,this.getReqUrl());}private String doReq(JSONObject reqParamsJson,String url){return HttpUtil.createPost(url).header("Authorization","Bearer "+ generateToken()).header(Header.CONTENT_TYPE, ContentType.JSON.toString()).body(reqParamsJson.toString()).execute().body();}private String generateToken(){return JWT.create().withIssuer(appId).withIssuedAt(new Date()).withJWTId(UUID.randomUUID().toString()).sign(Algorithm.HMAC256(appSecret));}}

账号同步子类

import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;
import java.util.Date;
import java.util.function.Function;@Service
@Slf4j
public class SyncAccountService extends AbstractSync<SyncAccount,SyncAccountBaseService> {@Resourceprivate SyncAccountBaseService syncAccountBaseService;@Value("${xxx}")private String reqUrl;@Value("${xxx}")private String callbackUrl;@Overrideprotected String getReqUrl() {return reqUrl;}@Overrideprotected String getCallbackUrl() {return callbackUrl;}@Overrideprotected String getReqFailedMsg() {return "调用账号同步-回调接口失败,请查看";}@Overrideprotected String getCallbackFailedMsg() {return "调用账号同步接口失败,请查看";}@Overrideprotected Class<SyncAccount> entityClass() {return SyncAccount.class;}@Overrideprotected SyncAccountBaseService getBaseService() {return syncAccountBaseService;}@Overrideprotected Function<SyncAccount, Date> sortFunc() {return SyncAccount::getRequestLogCreateTime;}@Overrideprotected SFunction<SyncAccount, String> bizIdFunc() {return SyncAccount::getAppAccountId;}@Overrideprotected Function<SyncAccount, String> callbackIdFunc() {return SyncAccount::getRequestLogId;}@Override@Transactional@Scheduled(cron = "0 */30 * * * ?")public void sync() {this.doSync();}}

组织同步子类

import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;
import java.util.Date;
import java.util.function.Function;@Service
@Slf4j
public class SyncOrgService extends AbstractSync<SyncOrg,SyncOrgBaseService> {@Resourceprivate SyncOrgBaseService syncOrgBaseService;@Value("xxx")String reqUrl;@Value("xxx")String callbackUrl;@Overridepublic String getReqUrl() {return reqUrl;}@Overridepublic String getCallbackUrl() {return callbackUrl;}@Overridepublic String getReqFailedMsg() {return "调用组织同步-回调接口失败,请查看";}@Overridepublic String getCallbackFailedMsg() {return "调用组织同步接口失败,请查看";}@Overrideprotected Class<SyncOrg> entityClass() {return SyncOrg.class;}@Overrideprotected SyncOrgBaseService getBaseService() {return syncOrgBaseService;}@Overrideprotected Function<SyncOrg, Date> sortFunc() {return SyncOrg::getRequestLogCreateTime;}@Overrideprotected SFunction<SyncOrg, String> bizIdFunc() {return SyncOrg::getIdtOrgId;}@Overrideprotected Function<SyncOrg, String> callbackIdFunc() {return SyncOrg::getRequestLogId;}@Override@Transactional@Scheduled(cron = "0 */30 * * * ?")public void sync() {this.doSync();}}

模板方法还有一个典型运用场景 AQS(抽象队列同步器)

相关文章:

  • latex设置背景颜色
  • IMDB影评情感分析项目
  • Elasticsearch深度攻略:核心概念与实践应用
  • iwebsec靶场 解析漏洞通关笔记2-Nginx解析漏洞
  • 【YashanDB知识库】YashanDB-OCI-快速上手
  • selenium 显示等待12种预置条件包括定制等待条件
  • 如何改变音频声音大小?关于改变音频大小的方法介绍
  • 线程与线程安全,生产消费者模型
  • Python+appium自动化+夜神模拟器inspector部署验证
  • 【工具类】证书自动续签免费版 正式发布
  • fiddler抓包07_抓IOS手机请求
  • Pinia从安装到使用
  • Metasploit渗透测试之服务端漏洞利用
  • 在vue2项目中使用dart-sass
  • 【JavaEE】——内存可见性问题
  • [ JavaScript ] 数据结构与算法 —— 链表
  • 【面试系列】之二:关于js原型
  • CentOS 7 修改主机名
  • egg(89)--egg之redis的发布和订阅
  • Github访问慢解决办法
  • HTTP--网络协议分层,http历史(二)
  • JavaSE小实践1:Java爬取斗图网站的所有表情包
  • Mac 鼠须管 Rime 输入法 安装五笔输入法 教程
  • nodejs实现webservice问题总结
  • node入门
  • PAT A1050
  • python学习笔记 - ThreadLocal
  • Solarized Scheme
  • SpringCloud(第 039 篇)链接Mysql数据库,通过JpaRepository编写数据库访问
  • SQLServer之创建数据库快照
  • storm drpc实例
  • 看完九篇字体系列的文章,你还觉得我是在说字体?
  • 前端代码风格自动化系列(二)之Commitlint
  • 前端技术周刊 2018-12-10:前端自动化测试
  • 数据可视化之 Sankey 桑基图的实现
  • 在weex里面使用chart图表
  • 这几个编码小技巧将令你 PHP 代码更加简洁
  • ​LeetCode解法汇总2670. 找出不同元素数目差数组
  • ​字​节​一​面​
  • "无招胜有招"nbsp;史上最全的互…
  • ######## golang各章节终篇索引 ########
  • #includecmath
  • #NOIP 2014# day.2 T2 寻找道路
  • $HTTP_POST_VARS['']和$_POST['']的区别
  • (6)添加vue-cookie
  • (Java入门)抽象类,接口,内部类
  • (Redis使用系列) Springboot 使用redis实现接口Api限流 十
  • (超简单)使用vuepress搭建自己的博客并部署到github pages上
  • (附源码)springboot码头作业管理系统 毕业设计 341654
  • (三)c52学习之旅-点亮LED灯
  • (转)IIS6 ASP 0251超过响应缓冲区限制错误的解决方法
  • (转)关于如何学好游戏3D引擎编程的一些经验
  • .dat文件写入byte类型数组_用Python从Abaqus导出txt、dat数据
  • .NET 8 编写 LiteDB vs SQLite 数据库 CRUD 接口性能测试(准备篇)
  • .NET 常见的偏门问题