一、利用阿里的開源數據庫同步工具-canal來解析不一樣的數據庫表binlog日誌,解析完成的數據,咱們要入庫不一樣的數據庫,不一樣的表。
二、每一個表對應一個Mapper類,插入不一樣的表,咱們須要選擇不一樣的Mapper來執行同一個函數:insertSelective
三、普通的完成方式,咱們須要根據不一樣的表名採用「if」條件判斷,選擇不一樣的Mapper,這樣的代碼是比較冗餘的。java
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 ""; }
一、註解的值就是表的名字。
二、Mapper實現接口IProcessor,傳入操做對象的類型spring
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); } }