@Override public <T> void uploadToES(String storeCd, String posId, String indexName, String tableName, List<T> list) { BulkRequest request = new BulkRequest(); LocalDateTime now = LocalDateTime.now(); String date = now.format(DateTimeFormatter.ofPattern("yyyy.MM.dd")); indexName = indexName + date; int rowCount = list.size(); for (T t : list) { ElasticsearchDTO elasticsearchDTO = new ElasticsearchDTO(); elasticsearchDTO.setWriteTime(now); elasticsearchDTO.setStoreCd(storeCd); elasticsearchDTO.setPosId(posId); elasticsearchDTO.setTable(tableName); elasticsearchDTO.setImpFlg("0"); elasticsearchDTO.setRowCount(rowCount); elasticsearchDTO.setRowData(GsonUtils.toJson(t)); String s = GsonUtils.toJson(elasticsearchDTO); request.add(new IndexRequest(indexName).source(s, XContentType.JSON)); } BulkResponse bulk = null; try { bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT); } catch (IOException e) { e.printStackTrace(); } if (bulk.status().getStatus() == 200) { System.out.println("批量插入成功!"); } } 帮我优化以上代码, 并添加log, 添加判断
时间: 2024-02-01 22:04:43 浏览: 80
好的,以下是优化后的代码,添加了日志输出和异常处理,并对参数进行了判断和校验:
```java
@Override
public <T> void uploadToES(String storeCd, String posId, String indexName, String tableName, List<T> list) {
if (StringUtils.isBlank(storeCd) || StringUtils.isBlank(posId) || StringUtils.isBlank(indexName) || StringUtils.isBlank(tableName) || CollectionUtils.isEmpty(list)) {
log.error("参数不能为空!");
return;
}
LocalDateTime now = LocalDateTime.now();
String date = now.format(DateTimeFormatter.ofPattern("yyyy.MM.dd"));
indexName = indexName + date;
int rowCount = list.size();
BulkRequest request = new BulkRequest();
for (T t : list) {
ElasticsearchDTO elasticsearchDTO = new ElasticsearchDTO();
elasticsearchDTO.setWriteTime(now);
elasticsearchDTO.setStoreCd(storeCd);
elasticsearchDTO.setPosId(posId);
elasticsearchDTO.setTable(tableName);
elasticsearchDTO.setImpFlg("0");
elasticsearchDTO.setRowCount(rowCount);
elasticsearchDTO.setRowData(GsonUtils.toJson(t));
String s = GsonUtils.toJson(elasticsearchDTO);
request.add(new IndexRequest(indexName).source(s, XContentType.JSON));
}
try {
BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
if (bulk.status().getStatus() == 200) {
log.info("批量插入成功!");
} else {
log.error("批量插入失败!");
}
} catch (IOException e) {
log.error("批量插入异常!", e);
}
}
```
希望这个答案对您有帮助!
阅读全文