您好,登錄后才能下訂單哦!
1、利用阿里的開源數據庫同步工具-canal來解析不同的數據庫表binlog日志,解析完成的數據,我們要入庫不同的數據庫,不同的表。
2、每個表對應一個Mapper類,插入不同的表,我們需要選擇不同的Mapper來執行同一個函數:insertSelective
3、普通的完成方式,我們需要根據不同的表名采用“if”條件判斷,選擇不同的Mapper,這樣的代碼是比較冗余的。
package com.jane.binlog.dao;
public interface IProcessor<T> {
int insertSelective(T record);
int updateSelective(T record);
}
package com.jane.binlog.dao;
import java.lang.annotation.*;
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ProcessorMapper {
String value() default "";
}
1、注解的值就是表的名字。
2、Mapper實現接口IProcessor,傳入操作對象的類型
import java.util.Date;
@Repository
@ProcessorMapper("pos_sale")
public interface PosSaleMapper extends IProcessor<PosSale> {
int insert(PosSale record);
}
package com.jane.binlog.service;
import com.alibaba.fastjson.JSONObject;
import com.jane.binlog.dao.IProcessor;
import com.jane.binlog.dao.ProcessorMapper;
import com.jane.binlog.entity.PosSale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
@Service
public class PosSaleService {
private static Logger LOG = LoggerFactory.getLogger(PosSaleService.class);
public static Map<String, Class> map = new HashMap<>();
//定義表和對象的關系
static {
map.put("pos_sale", PosSale.class);
}
private Map<String, IProcessor> mapperMap = new HashMap<String, IProcessor>();
@Autowired
private ApplicationContext applicationContext;
//利用spring上下文,注入帶有自定義注解的所有mapper到一個hashmap中。
@PostConstruct
public void init() {
String[] classNames = applicationContext.getBeanNamesForAnnotation(ProcessorMapper.class);
for (String name: classNames) {
Class<?> type = applicationContext.getType(name);
boolean posSaleMapper = type.isAnnotationPresent(ProcessorMapper.class);
if (posSaleMapper) {
String value = type.getAnnotation(ProcessorMapper.class).value();
mapperMap.put(value, (IProcessor) applicationContext.getBean(name));
}
}
}
/**
* 數據寫入操作
* @param table
* @param data
* @param op
*/
public void binlogInsert(String table, Map<String, Object> data, String op) {
try {
//獲取表對應的對象類
Class clazz = map.get(table);
//組裝對象數據
Object obj = this.assumePosSale(data, clazz);
//實現寫操作
IProcessor processor = mapperMap.get(table);
processor.insertSelective(obj);
} catch(Exception e) {
throw e;
}
}
/**
* 把數據map轉化為對應表對象
* @param data
* @param clazz
* @return
*/
private Object assumePosSale(Map<String, Object> data, Class clazz) {
return JSONObject.parseObject(JSONObject.toJSONString(data), clazz);
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。