Spring boot,jdbc 模板在手动应用程序 jar 启动后工作,但不能通过 cron。背后的原因可能是啥?

Posted

技术标签:

【中文标题】Spring boot,jdbc 模板在手动应用程序 jar 启动后工作,但不能通过 cron。背后的原因可能是啥?【英文标题】:Spring boot, jdbc template works after manual application jar start, but not via cron. What could be the reason behind?Spring boot,jdbc 模板在手动应用程序 jar 启动后工作,但不能通过 cron。背后的原因可能是什么? 【发布时间】:2021-12-26 14:00:33 【问题描述】:

我在连接到 Oracle 数据库的 Amazon Ec2 上使用 Spring Boot 应用程序。 application.properties 文件具有以下相关属性-

hibernate.dialect=org.hibernate.dialect.Oracle12cDialect
hibernate.show_sql=true
hibernate.format_sql=true

# dbcp2 settings
spring.datasource.dbcp2.initial-size=10
spring.datasource.dbcp2.max-total=100
spring.datasource.dbcp2.pool-prepared-statements=true
spring.jdbc.template.max-rows=500
spring.datasource.dbcp2.max-open-prepared-statements=100

logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG
logging.level.org.springframework.jdbc.core.StatementCreatorUtils=TRACE

# Schema
spring.appds.jdbcurl = jdbc:oracle:thin:@xx.r.zz.tt:1521/tttt
spring.appds.username = userAPP
spring.appds.password = passwordApp
spring.appds.driverClassName = oracle.jdbc.OracleDriver

应用程序 jar 使用根文件夹中的根权限通过 cron 运行。

从那时起,应用程序就没有为 jdbctemplate 查询返回数据。

SELECT *
FROM TABLE(lic.skd_es_i.e_g_app_sh_li(key => 54234
, date_from => NULL
, date_to => NULL
, use_country => 'IT'
, work_title => ''
, source => 'LOCAL'));

但是相同的查询总是在数据库上运行。

今天当我通过手动导航到 jar 位置重新启动 spring boot 应用程序 jar 时,它可以工作。

我很想知道背后的原因是什么?

【问题讨论】:

【参考方案1】:

当我通过手动导航到 jar 位置并启动应用程序来启动应用程序时,查询开始工作。

然后我意识到问题出在 Spring Boot 应用程序的工作目录上。 cron 使用 'root' 作为工作目录启动应用程序 jar,而 Spring boot jar 期望配置文件 - application.properties 或 application.yml - 在 4 个预定位置按以下优先顺序:

    当前目录的 /config 子目录 当前目录 类路径 /config 包 类路径根

因此将 cron 作业的工作目录指向正确的位置(在本例中为 spring boot jar 位置),数据源已正确加载。

参考-https://www.baeldung.com/spring-properties-file-outside-jar

【讨论】:

以上是关于Spring boot,jdbc 模板在手动应用程序 jar 启动后工作,但不能通过 cron。背后的原因可能是啥?的主要内容,如果未能解决你的问题,请参考以下文章

使用 jdbc 模板自动装配数据源问题的 Spring Boot 自动配置

Spring Boot使用JDBC方式连接MySQL

spring-boot:数据库中断后jdbc重新连接

Spring Boot 和 JDBCTemplate简介: JDBC Template

运行 Spring Boot 简单应用程序时找不到 Oracle 驱动程序

独立使用时 spring-boot-starter-jdbc 的问题