?一、初始化MYSQL數據
public boolean initMysql() throws Exception {log.info("initMysql.start");//獲取所連接的數據庫名稱 String database = systemMapper.getDatabase();if (StringUtils.isBlank(database)) {throw new BusinessException("連接數據庫失敗,數據庫不存在");}//當庫中沒有表、則執行sql腳本if (systemMapper.countTable(database) == 0) {SqlSession sqlSession = sqlSessionFactory.openSession();Connection conn = sqlSession.getConnection();String mysqlInitPath="config/mysql/init.sql";ClassPathResource rc = new ClassPathResource(mysqlInitPath);EncodedResource er = new EncodedResource(rc, "utf-8");ScriptUtils.executeSqlScript(conn, er);log.info("initMysql.db:" + database + ".end");}log.info("initMysql.end");return true; }
其中SystemMapper為
@Mapper public interface SystemMapper {//獲得當前數據庫表的數量@Select("select count(*) from information_schema.TABLES where TABLE_SCHEMA= #{schema}")int countTable(@Param("schema")String schema);//===獲得當前連接的數據庫名稱@Select("select database()")String getDatabase(); }
二、初始化ES數據
public boolean initEs() throws Exception {log.info("initEs.start");// 讀取配置String artInfoMappingPath =config/es/art_info_index_mapping.jsonString artInfoMapping = ResourceUtil.readStr(artInfoMappingPath, StandardCharsets.UTF_8);// 創建博文索引String esIndex="wechat"createIndexIfNotExist(esIndex, artInfoMapping);// 創建別名String?alias="art_info";addAlias(alias, esIndex); return true; }
?如果索引不存在就創建es索引
private void createIndexIfNotExist(String index, String mapping) {// 判斷索引存不存在if (StrUtil.isBlank(index) || esAggregateService.indexExist(index)) {return;}log.info("initEs --> index: {}", index);// 創建索引CreateIndexRequest request = new CreateIndexRequest(index);Settings.Builder settings = Settings.builder().put("max_result_window", 100000);request.settings(settings);request.mapping(mapping, XContentType.JSON);createIndex(request);}
?
public void createIndex(CreateIndexRequest request) {try {CreateIndexResponse response = elasticSearchClient.indices().create(request, RequestOptions.DEFAULT);log.info("create index: {}, isAcknowledged: {}", response.index(), response.isAcknowledged());} catch (IOException e) {log.error("ES 索引創建失敗 --> ", e);throw new BusinessException(ResultCode.INTERNAL_SERVER_ERROR);} }
?根據需要、添加es別名
@Override public void addAlias(String alias, String... index) {// 構建請求參數IndicesAliasesRequest indicesAliasesRequest = new IndicesAliasesRequest();IndicesAliasesRequest.AliasActions aliasActions = new IndicesAliasesRequest.AliasActions(IndicesAliasesRequest.AliasActions.Type.ADD).indices(index).alias(alias);indicesAliasesRequest.addAliasAction(aliasActions);try {AcknowledgedResponse response = elasticSearchClient.indices().updateAliases(indicesAliasesRequest, RequestOptions.DEFAULT);log.info("add alias --> index: {}, alias: {}, isAcknowledged: {}", index, alias, response.isAcknowledged());} catch (IOException e) {log.error("ES 別名創建失敗 --> ", e);throw new BusinessException(ResultCode.INTERNAL_SERVER_ERROR);} }