springBoot+MybatisPlus 监听表 修删操作 同步数据至ES
在Spring Boot项目中使用MyBatis Plus监听表的修改和删除操作并同步数据至Elasticsearch,你可以通过实现MybatisPlusInterceptor
接口来拦截相应的操作,并使用Elasticsearch的客户端进行数据同步。
以下是一个简化的例子:
- 首先,添加MyBatis Plus和Elasticsearch依赖到你的
pom.xml
文件中。
<!-- MyBatis Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>你的版本号</version>
</dependency>
<!-- Elasticsearch -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>你的版本号</version>
</dependency>
- 创建一个拦截器实现
MybatisPlusInterceptor
接口。
import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.update.Update;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.util.Properties;
@Component
public class MybatisPlusInterceptorConfig extends MybatisPlusInterceptor {
private final RestHighLevelClient restHighLevelClient;
public MybatisPlusInterceptorConfig(RestHighLevelClient restHighLevelClient) {
this.restHighLevelClient = restHighLevelClient;
// 添加分页插件
this.addInnerInterceptor(new PaginationInnerInterceptor());
// 添加监听插件
this.addInnerInterceptor(new MyInterceptor());
}
@Intercepts({
@Signature(type = StatementHandler.class, method = "update", args = {Connection.class, Object.class}),
@Signature(type = StatementHandler.class, method = "delete", args = {Connection.class, Object.class})
})
static class MyInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
BoundSql boundSql = statementHandler.getBoundSql();
String sql = boundSql.getSql
评论已关闭