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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。