一、初始化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);} }