您的位置:首页 > 数据库

项目启动先于数据库启动时项目启动失败的解决方法

2018-03-15 22:36 260 查看
我们知道,当服务启动时会根据xml中配置的数据库信息连接数据库。假如数据库无法连接,项目就会启动失败。那么,假如数据库启动速度比项目的启动速度慢还怎么办呢?一种方法是我们可以循环加载含有数据库连接信息的xml配置文件(也就是循环连接数据库)。代码如下:List<String> configLocations = new ArrayList<String>();
configLocations.add("/../conf/appContext.xml"); //将配置文件路径字符串放入集合中
for(Integer i=1;i<60;i++){
logger.info(i+" TIME load configuration file");
try {
//加载配置文件
applicationContext = new FileSystemXmlApplicationContext(
configLocations.toArray(new String[] {}));
applicationContext.registerShutdownHook();
//配置文加载成功的话就跳出循环
logger.info(i+" TIME load configuration file SUCCESS");
break;
} catch (Exception e) {
logger.warn(i+" TIME load configuration file FAIL", e);
}
//若达到次数上限,直接抛出异常不再catch
if(i.equals(59)){
applicationContext = new FileSystemXmlApplicationContext(
configLocations.toArray(new String[] {}));
applicationContext.registerShutdownHook();
}
//若加载配置文件失败就等待5秒,等待数据库启动
Thread.sleep(5000);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: