linwe
2024-08-09 8b7258c9427882bb1798f1502eaa35184c6e374e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package org.springblade.common.interceptor;
 
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.common.constant.EsTableConstant;
import org.springblade.common.utils.SQLParseUtils;
import org.springblade.es.service.ElasticsearchDocumentService;
import org.springblade.es.vo.EsParam;
import org.springblade.modules.article.entity.Article;
import org.springblade.modules.house.entity.HouseEntity;
import org.springblade.modules.house.entity.HouseholdEntity;
import org.springblade.modules.place.entity.PlaceEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
 
import java.util.List;
import java.util.Properties;
 
@Component
@Intercepts({
    @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class DataSyncInterceptor implements Interceptor {
 
    private static final Logger logger = LoggerFactory.getLogger(DataSyncInterceptor.class);
    @Lazy
    @Autowired
    private ElasticsearchDocumentService elasticsearchDocumentService;
 
    @Value("${elasticsearch.indexName}")
    private String indexName;
 
    /**
     * 拦截器在sql执行成功后同步到es,
     * 如果同步失败抛出异常,保证数据一致性
     *
     * @param invocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 获取StatementHandler,进行自定义处理
//        StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
 
        Object res = invocation.proceed();
        System.out.println("res = " + res);
 
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        if (args.length >= 2) {
            //参数
            Object parameter = invocation.getArgs()[1];
            BoundSql boundSql = ms.getBoundSql(parameter);
            //sql
            String sql = boundSql.getSql();
            sql = sql.replaceAll("\n", "");
            //获取表名
            String tableName = SQLParseUtils.getTableName(sql);
            String sqlType = SQLParseUtils.parseSQLType(sql);
            if (!Strings.isBlank(tableName)) {
                if (tableName.equals("jczz_article") ||
                    tableName.equals("jczz_house") ||
                    tableName.equals("jczz_household") ||
                    tableName.equals("jczz_place"))
                    syncDataAfterUpdate(tableName, sqlType, invocation.getArgs()[1]);
            }
        }
        return res;
    }
 
 
    /**
     * 数据同步
     *
     * @param tableName
     * @param sqlType
     * @param parameter
     */
    private void syncDataAfterUpdate(String tableName, String sqlType, Object parameter) {
        EsParam esParam = new EsParam();
        esParam.setIndexName(indexName);
        esParam.setTableName(tableName);
        // 判断操作类型
        if (sqlType.equals("INSERT")) {
            //insert 可用直接拦截到实体类
            if (tableName.equals("jczz_article")) {
                Article entity = (Article) parameter;
                elasticsearchDocumentService.addArticle(esParam, entity);
            }
            if (tableName.equals("jczz_place")) {
                PlaceEntity entity = (PlaceEntity) parameter;
                elasticsearchDocumentService.addPlace(esParam, entity);
            }
            if (tableName.equals("jczz_house")) {
                HouseEntity entity = (HouseEntity) parameter;
                elasticsearchDocumentService.addHouse(esParam, entity);
            }
            if (tableName.equals("jczz_household")) {
                HouseholdEntity entity = (HouseholdEntity) parameter;
                elasticsearchDocumentService.addHousehold(esParam, entity);
            }
        }
        if (sqlType.equals("UPDATE")) {
            //update 方法需要特殊处理
            if (tableName.equals("jczz_article")) {
                try {
                    Article entity = (Article) ((MapperMethod.ParamMap) parameter).get("param1");
                    if (entity != null && entity.getId() != null) {
                        esParam.setTableId(entity.getId().toString());
                        elasticsearchDocumentService.update(esParam, entity, EsTableConstant.articleList);
                    }
                } catch (Exception e) {
                    logger.error("jczz_article 更新失败!", e);
                }
            }
            if (tableName.equals("jczz_place")) {
                PlaceEntity entity = new PlaceEntity();
                PlaceEntity placeEntity = new PlaceEntity();
                if (parameter instanceof MapperMethod.ParamMap) {
                    placeEntity = (PlaceEntity) ((MapperMethod.ParamMap) parameter).get("param1");
                    if (placeEntity != null && null != placeEntity.getId()) {
                        setPlaceInfo(entity, placeEntity);
                        esParam.setTableId(entity.getId().toString());
                        elasticsearchDocumentService.update(esParam, entity, EsTableConstant.placeList);
                    }
                } else {
                    placeEntity = (PlaceEntity) parameter;
                    // 删除
                    esParam.setTableId(placeEntity.getId().toString());
                    elasticsearchDocumentService.removeByQuery(esParam);
                }
            }
            if (tableName.equals("jczz_house")) {
                HouseEntity houseEntity = new HouseEntity();
                HouseEntity entity = new HouseEntity();
                if (parameter instanceof MapperMethod.ParamMap) {
                    entity = (HouseEntity) ((MapperMethod.ParamMap) parameter).get("param1");
                    if (entity != null && entity.getId() != null) {
                        setHouseInfo(houseEntity, entity);
                        esParam.setTableId(entity.getId().toString());
                        elasticsearchDocumentService.update(esParam, entity, EsTableConstant.houseList);
                    }
                } else {
                    entity = (HouseEntity) parameter;
                    // 删除
                    esParam.setTableId(entity.getId().toString());
                    elasticsearchDocumentService.removeByQuery(esParam);
                }
            }
            if (tableName.equals("jczz_household")) {
                HouseholdEntity householdEntity = new HouseholdEntity();
                HouseholdEntity entity = new HouseholdEntity();
                if (parameter instanceof MapperMethod.ParamMap) {
                    try {
                        entity = (HouseholdEntity) ((MapperMethod.ParamMap) parameter).get("param1");
                        if (entity != null && entity.getId() != null) {
                            setHouseholdInfo(householdEntity, entity);
                            esParam.setTableId(entity.getId().toString());
                            elasticsearchDocumentService.update(esParam, entity, EsTableConstant.householdList);
                        }
                    } catch (Exception e) {
                        entity = (HouseholdEntity) ((MapperMethod.ParamMap) parameter).get("et");
                        if (entity != null && entity.getId() != null) {
                            setHouseholdInfo(householdEntity, entity);
                            esParam.setTableId(entity.getId().toString());
                            elasticsearchDocumentService.update(esParam, entity, EsTableConstant.householdList);
                        }
                    }
                } else {
                    entity = (HouseholdEntity) parameter;
                    // 删除
                    esParam.setTableId(entity.getId().toString());
                    elasticsearchDocumentService.removeByQuery(esParam);
                }
            }
        }
        // 删除处理
        if (sqlType.equals("DELETE")) {
            if (parameter instanceof MapperMethod.ParamMap) {
                List<Long> list = (List<Long>) ((MapperMethod.ParamMap) parameter).get("param1");
                esParam.setTableId(list.get(0).toString());
                elasticsearchDocumentService.removeByQuery(esParam);
            }
        }
    }
 
    /**
     * 场所值复制
     *
     * @param entity
     * @param placeEntity
     */
    private void setPlaceInfo(PlaceEntity entity, PlaceEntity placeEntity) {
        entity.setId(placeEntity.getId());
        entity.setPlaceName(placeEntity.getPlaceName());
        entity.setPrincipal(placeEntity.getPrincipal());
        entity.setPrincipalPhone(placeEntity.getPrincipalPhone());
        entity.setPrincipalIdCard(placeEntity.getPrincipalIdCard());
        entity.setLocation(placeEntity.getLocation());
    }
 
    /**
     * 房屋值复制
     *
     * @param entity
     * @param houseEntity
     */
    private void setHouseInfo(HouseEntity entity, HouseEntity houseEntity) {
        entity.setId(houseEntity.getId());
        entity.setHouseName(houseEntity.getHouseName());
    }
 
    /**
     * 住户值复制
     *
     * @param entity
     * @param householdEntity
     */
    private void setHouseholdInfo(HouseholdEntity entity, HouseholdEntity householdEntity) {
        entity.setId(householdEntity.getId());
        entity.setName(householdEntity.getName());
        entity.setPhoneNumber(householdEntity.getPhoneNumber());
        entity.setIdCard(householdEntity.getIdCard());
        entity.setCurrentAddress(householdEntity.getCurrentAddress());
    }
 
 
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
 
    @Override
    public void setProperties(Properties properties) {
    }
}