基于Java方式實(shí)現(xiàn)數(shù)據(jù)同步
本文實(shí)例為大家分享了Java方式實(shí)現(xiàn)數(shù)據(jù)同步的具體代碼,供大家參考,具體內(nèi)容如下
使用java方式實(shí)現(xiàn)兩個(gè)系統(tǒng)之間數(shù)據(jù)的同步。
業(yè)務(wù)背景
在新系統(tǒng)中設(shè)置定時(shí)任務(wù)需要實(shí)時(shí)把客戶系統(tǒng)中的數(shù)據(jù)及時(shí)同步過來,保持?jǐn)?shù)據(jù)的一致性。
實(shí)現(xiàn)邏輯
1.根據(jù)客戶提供的接口,本系統(tǒng)中采用Http的Post請(qǐng)求方式獲取接口數(shù)據(jù)。
2.由于客戶提供的接口必帶頁碼和頁面容量,因此會(huì)涉及到多次請(qǐng)求接口才能拿到全量數(shù)據(jù),因此相同的操作可以采用遞歸的方式進(jìn)行。
3.每次請(qǐng)求一次接口根據(jù)頁面容量(pageSize)可獲取多條數(shù)據(jù),此時(shí)可以采用批量添加數(shù)據(jù)庫的操作,使用批量SQL添加語句。
4.由于數(shù)據(jù)同步需要保持兩個(gè)系統(tǒng)數(shù)據(jù)的一致性,因此需要使用定時(shí)任務(wù)并規(guī)定同步頻率,例如:一天一次或者一天兩次。
5.定時(shí)任務(wù)的使用會(huì)產(chǎn)生數(shù)據(jù)重復(fù)的問題,因此根據(jù)某個(gè)唯一字段建立唯一索引來避免數(shù)據(jù)重復(fù)添加的問題。
6.唯一索引的建立可以避免同一記錄重復(fù)添加的問題,但是避免不了同一條記錄除唯一索引字段之外其它字段對(duì)應(yīng)數(shù)據(jù)發(fā)生變化問題,因此使用replace into添加SQL語句可以解決此問題。
提示: a. 如果發(fā)現(xiàn)表中已經(jīng)有此行數(shù)據(jù)(根據(jù)主鍵或者唯一索引判斷)則先刪除此行數(shù)據(jù),然后插入新的數(shù)據(jù)。 b. 不然的話,直接插入新的數(shù)據(jù)。
使用技術(shù)
1.設(shè)置定時(shí)任務(wù)。
2.采用Http的Post方式獲取接口數(shù)據(jù)。
3.涉及多頁數(shù)據(jù)采用遞歸方式循環(huán)調(diào)用。
4.批量操作數(shù)據(jù)庫(replace into)。
5.建立唯一索引避免重復(fù)插入數(shù)據(jù)。
代碼詳情
1.StudentMapper.java
/** ? ? ?* 批量添加數(shù)據(jù)同步接口學(xué)生數(shù)據(jù) ? ? ?* @param studentList ? ? ?* @return ? ? ?*/ ? ? int addBatchStudent(@Param(value = "studentList") List<Student> studentList);
2.SyncStudentServiceImpl.java代碼如下:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import ***.common.utils.HttpUtils;
import ***.common.utils.StringUtils;
import ***.entity.sync.Student;
import ***.mapper.sync.StudentMapper;
import ***.service.sync.SyncStudentService;
import ***.vo.StudentVO;
import lombok.extern.slf4j.Slf4j;
/**
?* 數(shù)據(jù)同步的學(xué)生實(shí)現(xiàn)類
?* @author hc
?* @create 2021/03/25 11:20
?* @version 1.0
?* @since 1.0
?*/
@Service
@Slf4j
public class SyncStudentServiceImpl implements SyncStudentService {
? ? @Autowired
? ? private StudentMapper studentMapper;
? ? @Autowired
? ? private HttpUtils httpUtils;
? ? @Override
? ? public void bulkAddStudent(StudentVO studentVO) {
? ? ?? ?log.info("調(diào)取學(xué)生接口傳的參數(shù)對(duì)象studentVO:"+studentVO);
? ? ?? ?log.info("開始調(diào)取學(xué)生接口獲取第" + studentVO.getPageIndex() + "頁數(shù)據(jù)");
? ? ?? ?//如何頁面容量小于100,則按100計(jì)算
? ? ?? ?if(studentVO.getPageSize() < 100) {
? ? ?? ??? ?studentVO.setPageSize(100);
? ? ?? ?}
? ? ? ? //根據(jù)當(dāng)前頁碼和頁面容量調(diào)取獲取學(xué)生數(shù)據(jù)接口
? ? ? ? JSONObject jsonObject = this.sendStudentHttpPost(studentVO);
? ? ? ? //判斷返回JSONObject是否為null
? ? ? ? if (StringUtils.isNotNull(jsonObject) && jsonObject.containsKey("errcode") && jsonObject.getInteger("errcode") == 0) {
? ? ? ? ? ? if(jsonObject.containsKey("data")){
? ? ? ? ? ? ?? ?JSONArray jsonArray = jsonObject.getJSONArray("data");
? ? ? ? ? ? ?? ?//通過判斷獲取的jsonObject對(duì)象中key值為data是否為null和其 jsonArray的長(zhǎng)度來判斷是否進(jìn)行遞歸
? ? ? ? ? ? ?? ?//提示:此判斷方法好于通過計(jì)算總頁碼的方式來遞歸拿數(shù)據(jù)(對(duì)獲取的total依賴過大,因此放棄此方式)
? ? ? ? ? ? ?? ?if(jsonObject.getString("data") != null && jsonArray.size() > 0) {
? ? ? ? ? ? ?? ? ? log.info("當(dāng)前數(shù)據(jù)加載到幾頁》》》》:{}", studentVO.getPageIndex());
? ? ?? ? ? ? ? ? ? //調(diào)取批量添加數(shù)據(jù)
? ? ? ? ? ? ? ? ? ?this.addStudentCycleData(jsonObject, studentVO);
? ? ? ? ? ? ? ? ? ?//頁碼加1,繼續(xù)調(diào)取下一頁數(shù)據(jù)
? ? ? ? ? ? ? ??? ? ? studentVO.setPageIndex(studentVO.getPageIndex() + 1);
? ? ? ? ? ? ? ?? ? ? //采用遞歸方式直至循環(huán)結(jié)束
? ? ? ? ? ? ? ? ? ?this.bulkAddStudent(studentVO);
? ? ? ? ? ? ?? ?}else {
?? ??? ??? ??? ??? ?log.info("學(xué)生數(shù)據(jù)同步結(jié)束》》》");
?? ??? ??? ??? ?}
? ? ? ? ? ? }
?? ??? ?}
? ? }
? ? /**
? ? ?* 批量添加學(xué)生數(shù)據(jù)
? ? ?* @param jsonObject
? ? ?* @param areaVO
? ? ?* @return
? ? ?*/
? ? public void addStudentCycleData(JSONObject jsonObject, StudentVO studentVO){
? ? ?? ?List<Student> studentList = null;
? ? ? ? //判斷jsonArray時(shí)候?yàn)榭?
? ? ? ? if (jsonObject != null && StringUtils.isNotBlank(jsonObject.getString("data"))) {
?? ? ? ? ? ?//把JsonArray轉(zhuǎn)成對(duì)應(yīng)實(shí)體類集合
? ? ? ? ?? ?studentList = JSONObject.parseArray(jsonObject.getString("data"), Student.class);
? ? ? ? }
? ? ? ? try {
? ? ? ? ?? ?log.info("學(xué)生接口第" + studentVO.getPageIndex() + "頁數(shù)據(jù)開始入庫...");
? ? ? ? ?? ?//調(diào)取方法批量進(jìn)行添加學(xué)生數(shù)據(jù)
? ? ? ? ?? ?studentMapper.addBatchStudent(studentList);
? ? ? ? ?? ?log.info("學(xué)生接口第" + studentVO.getPageIndex() + "頁數(shù)據(jù)入庫成功...");
?? ??? ?} catch (Exception e) {
?? ??? ??? ?log.error("學(xué)生批量添加數(shù)據(jù)庫異常:{}", e.getMessage());
?? ??? ?}
? ? }
? ? /**
? ? ?* 根據(jù)studentVO(當(dāng)前頁碼和頁面容量)發(fā)送獲取學(xué)生數(shù)據(jù)的請(qǐng)求
? ? ?* @param studentVO
? ? ?* @return
? ? ?*/
? ? public JSONObject sendStudentHttpPost(StudentVO studentVO){
? ? ?? ?JSONObject jsonObject = null;
?? ??? ?String studentUrl = "http://*****/async-api/jc/student";
? ? ?? ?try {
? ? ?? ??? ?if (StringUtils.isNotEmpty(studentUrl)) {
? ? ? ? ?? ??? ?Map<String, Object> param = new HashMap<>();
? ? ? ? ?? ??? ?param.put("pageIndex", studentVO.getPageIndex());
? ? ? ? ?? ??? ?param.put("pageSize", studentVO.getPageSize());
? ? ? ? ? ? ? ? log.info("開始發(fā)起http請(qǐng)求...");
? ? ? ? ? ? ? ? jsonObject = httpUtils.sendHttpPost(param, studentUrl);
? ? ?? ??? ?}
?? ??? ?} catch (Exception e) {
?? ??? ??? ?log.error("調(diào)取客戶學(xué)生同步接口出現(xiàn)異常:{},頁面容量為:{},頁碼:{}", e.getMessage(),?
?? ??? ??? ?studentVO.getPageSize(), studentVO.getPageIndex());
?? ??? ?}
? ? ? ? return jsonObject;
? ? }
}3.StudentVO.java代碼如下:
import lombok.Data;
/**
?* 數(shù)據(jù)同步接口獲取學(xué)生數(shù)據(jù)傳的參數(shù)VO類
?* @author hc
?* @create 2021/3/11 10:35
?* @version 1.0
?* @since 1.0
?*/
@Data
public class StudentVO{
?? ?//當(dāng)前頁碼(初始值為0)
?? ?private Integer pageIndex = 0;
?? ?//頁碼容量
?? ?private Integer pageSize;
}4.HttpUtils.java代碼如下:
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
/**
?* Http請(qǐng)求工具類
?* @author hc
?* @create 2021/3/4
?* @version 1.0
?*/
@Component
@Slf4j
public class HttpUtils {
? ? @Autowired
? ? private RestTemplate restTemplate;
?? ?
? ? /**
? ? ?* 發(fā)送http的post請(qǐng)求方法
? ? ?* @param param
? ? ?* @return
? ? ?*/
? ? public JSONObject sendHttpPost(Integer type, Map<String, Object> param, String url){
?? ? ? ?log.info("調(diào)取同步接口Url:{}", url);
? ? ? ? JSONObject jsonObject = null;
?? ??? ?//發(fā)起http的post準(zhǔn)備工作
?? ??? ?HttpHeaders httpHeaders = new HttpHeaders();
?? ??? ?httpHeaders.add("Content-Type", "application/json");
?? ??? ?HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(param, httpHeaders);
?? ??? ?ResponseEntity<String> response = null;
?? ??? ?try {
?? ??? ? ? ?log.info("param參數(shù)為:{}",param.toString());
?? ??? ??? ?response = restTemplate.postForEntity(url, httpEntity, String.class);
?? ??? ?} catch (HttpClientErrorException e) {
?? ??? ??? ?log.error("發(fā)起http請(qǐng)求報(bào)錯(cuò)信息:{}",e.getResponseBodyAsString());
?? ??? ?}
?? ??? ?String bodyData = response.getBody();
?? ??? ?if (StringUtils.isNotEmpty(bodyData)) {
?? ??? ??? ?jsonObject = JSONObject.parseObject(bodyData);
?? ??? ?}
? ? ? ? return jsonObject;
? ? }
}5.StudentMapper.xml的SQL語句如下:
<!-- 批量添加數(shù)據(jù)同步接口中獲取的學(xué)生數(shù)據(jù) -->
<insert id="addBatchStudent" parameterType="***.entity.sync.Student">
?? ?replace into xf_clue_sync_student(id, student_code, student_name, status, create_date, update_date)
?? ?<foreach collection="studentList" item="student" open="values" separator="," >
?? ? ? (#{student.id,jdbcType=BIGINT}, #{student.studentCode,jdbcType=INTEGER}, #{student.studentName,jdbcType=VARCHAR},?
?? ? ? ?#{student.status,jdbcType=INTEGER}, #{student.createDate,jdbcType=VARCHAR}, #{student.updateDate,jdbcType=VARCHAR})
?? ?</foreach>
</insert>功能小結(jié)
1.定時(shí)任務(wù)配置相關(guān)代碼此處不再展示,SpringBoot框架使用注解的方式即可設(shè)置定時(shí)任務(wù)以及調(diào)取頻率。
2.數(shù)據(jù)同步接口開發(fā)需要根據(jù)具體應(yīng)用場(chǎng)景采用不同的方法,需視情況而定,例如:也可以使用kettle工具等等。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot 普通類調(diào)用Bean對(duì)象的一種方式推薦
這篇文章主要介紹了SpringBoot 普通類調(diào)用Bean對(duì)象的一種方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
Java之SpringBoot集成ActiveMQ消息中間件案例講解
這篇文章主要介紹了Java之SpringBoot集成ActiveMQ消息中間件案例講解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07
Spring Boot通過Junit實(shí)現(xiàn)單元測(cè)試過程解析
這篇文章主要介紹了Spring Boot通過Junit實(shí)現(xiàn)單元測(cè)試過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01
關(guān)于IntelliJ IDEA 打包代碼報(bào)錯(cuò)的問題
這篇文章主要介紹了關(guān)于IntelliJ IDEA 打包代碼報(bào)錯(cuò)的問題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03
springBoot使用openfeign來遠(yuǎn)程調(diào)用的實(shí)現(xiàn)
這篇文章主要介紹了springBoot使用openfeign來遠(yuǎn)程調(diào)用的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
Springboot整合freemarker和相應(yīng)的語法詳解
FreeMarker是一款Spring官方推薦使用的模板引擎。接下來通過本文給大家介紹Springboot整合freemarker和相應(yīng)的語法,感興趣的朋友一起看看吧2021-09-09
Java通過動(dòng)態(tài)代理實(shí)現(xiàn)一個(gè)簡(jiǎn)單的攔截器操作
這篇文章主要介紹了Java通過動(dòng)態(tài)代理實(shí)現(xiàn)一個(gè)簡(jiǎn)單的攔截器操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
關(guān)于spring事務(wù)傳播行為非事務(wù)方式的理解
這篇文章主要介紹了對(duì)spring事務(wù)傳播行為非事務(wù)方式的全面理解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
基于LinkedHashMap實(shí)現(xiàn)LRU緩存
LinkedHashMap是Java集合中一個(gè)常用的容器,它繼承了HashMap, 是一個(gè)有序的Hash表。那么該如何基于LinkedHashMap實(shí)現(xiàn)一個(gè)LRU緩存呢?本文將介紹LinkedHashMap的實(shí)現(xiàn)原理,感興趣的同學(xué)可以參考一下2023-05-05
Java實(shí)現(xiàn)簡(jiǎn)單的飛機(jī)大戰(zhàn)游戲(敵機(jī)下落篇)
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)簡(jiǎn)單的飛機(jī)大戰(zhàn)游戲,敵機(jī)下落篇,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05

