实现增量数据索引
上一节中,我们为实现增量索引的加载做了充足的准备,使用到mysql-binlog-connector-java
开源组件来实现MySQL 的binlog监听,关于binlog的相关知识,大家可以自行网络查阅。或者可以mailto:[email protected]
本节我们将根据binlog 的数据对象,来实现增量数据的处理,我们构建广告的增量数据,其实说白了就是为了在后期能把广告投放到索引服务,实现增量数据到增量索引的生成。Let's code.
- 定义一个投递增量数据的接口(接收参数为我们上一节定义的binlog日志的转换对象)
/**
* ISender for 投递增量数据 方法定义接口
*
* @author <a href="mailto:[email protected]">Isaac.Zhang | 若初</a>
*/
public interface ISender {
void sender(MysqlRowData rowData);
}
- 创建增量索引监听器
/**
* IncrementListener for 增量数据实现监听
*
* @author <a href="mailto:[email protected]">Isaac.Zhang | 若初</a>
* @since 2019/6/27
*/
@Slf4j
@Component
public class IncrementListener implements Ilistener {
private final AggregationListener aggregationListener;
@Autowired
public IncrementListener(AggregationListener aggregationListener) {
this.aggregationListener = aggregationListener;
}
//根据名称选择要注入的投递方式
@Resource(name = "indexSender")
private ISender sender;
/**
* 标注为 {@link PostConstruct},
* 即表示在服务启动,Bean完成初始化之后,立刻初始化
*/
@Override
@PostConstruct
public void register() {
log.info("IncrementListener register db and table info.");
Constant.table2db.forEach((tb, db) -> aggregationListener.register(db, tb, this));
}
@Override
public void onEvent(BinlogRowData eventData) {
TableTemplate table = eventData.getTableTemplate();
EventType eventType = eventData.getEventType();
//包装成最后需要投递的数据
MysqlRowData rowData = new MysqlRowData();
rowData.setTableName(table.getTableName());
rowData.setLevel(eventData.getTableTemplate().getLevel());
//将EventType转为OperationTypeEnum
OperationTypeEnum operationType = OperationTypeEnum.convert(eventType);
rowData.setOperationTypeEnum(operationType);
//获取模版中该操作对应的字段列表
List<String> fieldList = table.getOpTypeFieldSetMap().get(operationType);
if (null == fieldList) {
log.warn("{} not support for {}.", operationType, table.getTableName());
return;
}
for (Map<String, String> afterMap : eventData.getAfter()) {