Spring 预定线程未访问数据库
Spring scheduled thread is not accesing database
我想要实现的是每 30 分钟安排一次对我的数据库的查询,这个查询会给我带来许多记录和许多新任务要安排,这些新任务将对我的数据库和其他一些执行新的 CRUD 操作操作。
首先,我使用@EnableScheduling 来安排 "SELECT" 查询
@Service
@EnableScheduling
public class ScheduleUpdatesTransaction {
final static Logger logger = Logger.getLogger(ScheduleUpdatesTransaction.class);
@Scheduled(fixedDelay = 10000)
public void executeTransaction() {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
List<Object[]> programUpdatesList = playerDAO.getUpdatesByTimeIterval(myCustomDateTime);//Ok, it access database an retrieve data
for(Object[] element: programUpdatesList){
Long seconds = Long.parseLong(element[0].toString());
Long myKey = Long.parseLong(element[1].toString());
executor.schedule(new ScheduleThreadTransaction(myKey), seconds , TimeUnit.SECONDS);//Ok, it triggers the task
}
executor.shutdown();
}
}
这是 ScheduleThreadTransaction class:
@Component
public class ScheduleThreadTransaction implements Runnable{
@Autowired
private PlayerTaskDAO playerTaskDAO;
private Long myIdentificator;
public ScheduleThreadTransaction() {
super();
}
public ScheduleThreadTransaction(Long identificator) {
myIdentificator = identificator;
}
public void run() {
try{
PlayerTask playerTask = playerTaskDAO.findOne(myIdentificator);// not working, java.lang.NullPointerException
//More CRUD operations here
}catch(Exception e){
e.printStackTrace();
}
}
public Long getMyIdentificator() {
return myIdentificator;
}
public void setMyIdentificator(Long myIdentificator) {
this.myIdentificator = myIdentificator;
}
}
问题是在调用 findOne 时,我得到 NullPointerException。有什么建议吗?我正在使用 Spring 4 和 JPA 2.1。
编辑:
我对配置进行了一些更改,这是我的 XML 配置:
<context:component-scan base-package="com.myproject"/>
<mvc:annotation-driven>
<mvc:message-converters>
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="serializationInclusion" value="NON_NULL"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<mvc:resources mapping="/images/*" location="/images/" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="persistenceUnitName" value="myProjectPersistence" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="HSQL" />
<property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/myConection" />
<property name="username" value="123456" />
<property name="password" value="654321" />
</bean>
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="/WEB-INF/velocity/"/>
</bean>
<bean id="statusUpdateService" class="com.myproject.StatusUpdateService" />
<bean id="scheduledExecutorFactoryBean" class="org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean" />
<bean id="scheduleThreadTransactionService" class="com.myproject.ScheduleThreadTransactionService" />
这是 ScheduleUpdatesTransaction class:
@Service
@EnableScheduling
public class ScheduleUpdatesTransaction {
final static Logger logger = Logger.getLogger(ScheduleUpdatesTransaction.class);
@Autowired
private PlayerCoreUpdateDAO playerCoreUpdateDAO;
@Autowired
StatusUpdateService statusUpdateService;
@Scheduled(fixedDelay = 100000)
public void executeTransaction() {
Util util = new Util();
List<Object[]> programUpdatesList = playerCoreUpdateDAO.getWeaponUpdatesByTimeIterval(new Date());
for(Object[] element: programUpdatesList){
Long seconds = Long.parseLong(element[2].toString());
String finishDate =element[3].toString();
Long myUpdateKey = Long.parseLong(element[0].toString());
System.out.println("UPGRADETIME " + seconds + " FINISHUPGRADETIME " + myUpdateKey);
statusUpdateService.executeTransaction(seconds, myUpdateKey);
}
}
}
StatusUpdateServiceclass:
@Service
public class StatusUpdateService {
final static Logger logger = Logger.getLogger(StatusUpdateService.class);
@Autowired
private ScheduledExecutorFactoryBean scheduledExecutorFactoryBean;
@Autowired
private Provider<ScheduleThreadTransactionService> runnableFactory;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void executeTransaction(Long seconds, Long myUpdateKey){
try{
ScheduledExecutorService executor = scheduledExecutorFactoryBean.getObject();
ScheduleThreadTransactionService runnable = runnableFactory.get();
runnable.setElementKey(myUpdateKey);
executor.schedule(runnable, seconds, TimeUnit.SECONDS);
}catch(Exception e){
logger.error(e);
}
}
}
最后是 ScheduleThreadTransactionService class:
@Service
public class ScheduleThreadTransactionService implements Runnable{
final static Logger logger = Logger.getLogger(ScheduleThreadTransactionService.class);
private Long elementKey;
public ScheduleThreadTransactionService() {
}
public ScheduleThreadTransactionService(Long elementKey) {
this.elementKey = elementKey;
}
@Autowired
private PlayerCoreUpdateDAO playerCoreUpdateDAO;
//Adding @transactional throws an error
public void run() {
try{
PlayerCoreUpdate playerCoreUpdate = playerCoreUpdateDAO.findOne(elementKey);//It works!
playerCoreUpdateDAO.update(playerCoreUpdate);//Didn't work, need @transactional
}catch(Exception e){
logger.error(e);
}
}
public Long getElementKey() {
return elementKey;
}
public void setElementKey(Long elementKey) {
this.elementKey = elementKey;
}
public PlayerCoreUpdateDAO getPlayerCoreUpdateDAO() {
return playerCoreUpdateDAO;
}
public void setPlayerCoreUpdateDAO(PlayerCoreUpdateDAO playerCoreUpdateDAO) {
this.playerCoreUpdateDAO = playerCoreUpdateDAO;
}
}
添加@Transactional 给我这个错误:
2015-09-28 12:33:32,840 scheduledExecutorFactoryBean-1 错误 service.StatusUpdateService - org.springframework.beans.factory.NoSuchBeanDefinitionException: 没有为依赖项找到 [com.myproject.ScheduleThreadTransactionService] 类型的合格 bean:预期至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
是否有一个简短的修复来获得这个东西运行?
此致。
您正在使用 new 来实例化您的可运行 spring 组件。 Spring 如果您手动实例化,容器将无法注入依赖项。
您需要从bean 工厂获取runnable 的实例。一种更简洁的方法是使用工厂和查找方法注入。
如果您的所有 spring 配置都使用注释,则等效的查找方法将是
在您的 sheduleThreadTransaction class 中进行以下更改
@Autowired
private javax.inject.Provider<ScheduleThreadTransaction> runnableFactory;
在您的 executeTransaction 方法中
ScheduleThreadTransaction runnable = runnableFactory.get();
runnable.setIdentifier(myIdentifier);
您没有以正确的方式注入 spring bean,而是使用 new 创建引用,因此它不是上下文感知的 spring bean,因此 DAO 为 null,但是因为你已经在使用 spring 提供的调度/异步,你可以创建一个单例 bean,使用你想要的方法并在其中注入你所有的 DAO 和员工,并使调度程序调用异步的方法,所以你将避免自己创建一个线程执行器和相应的线程,让 spring 为你做这件事,这样至少执行器和服务将是上下文感知的。
@Component
public class ScheduleThreadTransactionService{
@Autowired
private PlayerTaskDAO playerTaskDAO;
@Async
public void callAsync(Long myIdentificator)
{
try{
PlayerTask playerTask = playerTaskDAO.findOne(myIdentificator);
//More CRUD operations here
}catch(Exception e){
e.printStackTrace();
}
}
}
将其注入您的调度程序
@Service
@EnableScheduling
public class ScheduleUpdatesTransaction {
@Autowired
private ScheduleThreadTransactionService service;
@Scheduled(fixedDelay = 10000)
public void executeTransaction()
{
for(Long key : playerDAO.getUpdatesByTimeIterval(myCustomDateTime))
service.callAsync(key);
}
}
请注意,您可能需要在 spring-conf.xml 中添加更多内容,共享使用 spring 3 + 的配置和 ConcurrentTaskExecutor ,但您可以检查其他实现spring provides ,因为可能有适合您需求的案例。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
">
<context:component-scan base-package = "your.package"/>
<task:annotation-driven executor="taskExecutor" proxy-target-class="false"/>
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ConcurrentTaskExecutor">
<property name="concurrentExecutor" ref="threadPoolExecutor" />
</bean>
<bean id="threadPoolExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" >
<property name="corePoolSize" value="25" />
<property name="maxPoolSize" value="50" />
<property name="queueCapacity" value="100" />
</bean>
</beans>
我想要实现的是每 30 分钟安排一次对我的数据库的查询,这个查询会给我带来许多记录和许多新任务要安排,这些新任务将对我的数据库和其他一些执行新的 CRUD 操作操作。
首先,我使用@EnableScheduling 来安排 "SELECT" 查询
@Service
@EnableScheduling
public class ScheduleUpdatesTransaction {
final static Logger logger = Logger.getLogger(ScheduleUpdatesTransaction.class);
@Scheduled(fixedDelay = 10000)
public void executeTransaction() {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
List<Object[]> programUpdatesList = playerDAO.getUpdatesByTimeIterval(myCustomDateTime);//Ok, it access database an retrieve data
for(Object[] element: programUpdatesList){
Long seconds = Long.parseLong(element[0].toString());
Long myKey = Long.parseLong(element[1].toString());
executor.schedule(new ScheduleThreadTransaction(myKey), seconds , TimeUnit.SECONDS);//Ok, it triggers the task
}
executor.shutdown();
}
}
这是 ScheduleThreadTransaction class:
@Component
public class ScheduleThreadTransaction implements Runnable{
@Autowired
private PlayerTaskDAO playerTaskDAO;
private Long myIdentificator;
public ScheduleThreadTransaction() {
super();
}
public ScheduleThreadTransaction(Long identificator) {
myIdentificator = identificator;
}
public void run() {
try{
PlayerTask playerTask = playerTaskDAO.findOne(myIdentificator);// not working, java.lang.NullPointerException
//More CRUD operations here
}catch(Exception e){
e.printStackTrace();
}
}
public Long getMyIdentificator() {
return myIdentificator;
}
public void setMyIdentificator(Long myIdentificator) {
this.myIdentificator = myIdentificator;
}
}
问题是在调用 findOne 时,我得到 NullPointerException。有什么建议吗?我正在使用 Spring 4 和 JPA 2.1。
编辑:
我对配置进行了一些更改,这是我的 XML 配置:
<context:component-scan base-package="com.myproject"/>
<mvc:annotation-driven>
<mvc:message-converters>
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<property name="serializationInclusion" value="NON_NULL"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<mvc:resources mapping="/images/*" location="/images/" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="persistenceUnitName" value="myProjectPersistence" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="HSQL" />
<property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/myConection" />
<property name="username" value="123456" />
<property name="password" value="654321" />
</bean>
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="/WEB-INF/velocity/"/>
</bean>
<bean id="statusUpdateService" class="com.myproject.StatusUpdateService" />
<bean id="scheduledExecutorFactoryBean" class="org.springframework.scheduling.concurrent.ScheduledExecutorFactoryBean" />
<bean id="scheduleThreadTransactionService" class="com.myproject.ScheduleThreadTransactionService" />
这是 ScheduleUpdatesTransaction class:
@Service
@EnableScheduling
public class ScheduleUpdatesTransaction {
final static Logger logger = Logger.getLogger(ScheduleUpdatesTransaction.class);
@Autowired
private PlayerCoreUpdateDAO playerCoreUpdateDAO;
@Autowired
StatusUpdateService statusUpdateService;
@Scheduled(fixedDelay = 100000)
public void executeTransaction() {
Util util = new Util();
List<Object[]> programUpdatesList = playerCoreUpdateDAO.getWeaponUpdatesByTimeIterval(new Date());
for(Object[] element: programUpdatesList){
Long seconds = Long.parseLong(element[2].toString());
String finishDate =element[3].toString();
Long myUpdateKey = Long.parseLong(element[0].toString());
System.out.println("UPGRADETIME " + seconds + " FINISHUPGRADETIME " + myUpdateKey);
statusUpdateService.executeTransaction(seconds, myUpdateKey);
}
}
}
StatusUpdateServiceclass:
@Service
public class StatusUpdateService {
final static Logger logger = Logger.getLogger(StatusUpdateService.class);
@Autowired
private ScheduledExecutorFactoryBean scheduledExecutorFactoryBean;
@Autowired
private Provider<ScheduleThreadTransactionService> runnableFactory;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void executeTransaction(Long seconds, Long myUpdateKey){
try{
ScheduledExecutorService executor = scheduledExecutorFactoryBean.getObject();
ScheduleThreadTransactionService runnable = runnableFactory.get();
runnable.setElementKey(myUpdateKey);
executor.schedule(runnable, seconds, TimeUnit.SECONDS);
}catch(Exception e){
logger.error(e);
}
}
}
最后是 ScheduleThreadTransactionService class:
@Service
public class ScheduleThreadTransactionService implements Runnable{
final static Logger logger = Logger.getLogger(ScheduleThreadTransactionService.class);
private Long elementKey;
public ScheduleThreadTransactionService() {
}
public ScheduleThreadTransactionService(Long elementKey) {
this.elementKey = elementKey;
}
@Autowired
private PlayerCoreUpdateDAO playerCoreUpdateDAO;
//Adding @transactional throws an error
public void run() {
try{
PlayerCoreUpdate playerCoreUpdate = playerCoreUpdateDAO.findOne(elementKey);//It works!
playerCoreUpdateDAO.update(playerCoreUpdate);//Didn't work, need @transactional
}catch(Exception e){
logger.error(e);
}
}
public Long getElementKey() {
return elementKey;
}
public void setElementKey(Long elementKey) {
this.elementKey = elementKey;
}
public PlayerCoreUpdateDAO getPlayerCoreUpdateDAO() {
return playerCoreUpdateDAO;
}
public void setPlayerCoreUpdateDAO(PlayerCoreUpdateDAO playerCoreUpdateDAO) {
this.playerCoreUpdateDAO = playerCoreUpdateDAO;
}
}
添加@Transactional 给我这个错误:
2015-09-28 12:33:32,840 scheduledExecutorFactoryBean-1 错误 service.StatusUpdateService - org.springframework.beans.factory.NoSuchBeanDefinitionException: 没有为依赖项找到 [com.myproject.ScheduleThreadTransactionService] 类型的合格 bean:预期至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
是否有一个简短的修复来获得这个东西运行?
此致。
您正在使用 new 来实例化您的可运行 spring 组件。 Spring 如果您手动实例化,容器将无法注入依赖项。
您需要从bean 工厂获取runnable 的实例。一种更简洁的方法是使用工厂和查找方法注入。
如果您的所有 spring 配置都使用注释,则等效的查找方法将是
在您的 sheduleThreadTransaction class 中进行以下更改
@Autowired
private javax.inject.Provider<ScheduleThreadTransaction> runnableFactory;
在您的 executeTransaction 方法中
ScheduleThreadTransaction runnable = runnableFactory.get();
runnable.setIdentifier(myIdentifier);
您没有以正确的方式注入 spring bean,而是使用 new 创建引用,因此它不是上下文感知的 spring bean,因此 DAO 为 null,但是因为你已经在使用 spring 提供的调度/异步,你可以创建一个单例 bean,使用你想要的方法并在其中注入你所有的 DAO 和员工,并使调度程序调用异步的方法,所以你将避免自己创建一个线程执行器和相应的线程,让 spring 为你做这件事,这样至少执行器和服务将是上下文感知的。
@Component
public class ScheduleThreadTransactionService{
@Autowired
private PlayerTaskDAO playerTaskDAO;
@Async
public void callAsync(Long myIdentificator)
{
try{
PlayerTask playerTask = playerTaskDAO.findOne(myIdentificator);
//More CRUD operations here
}catch(Exception e){
e.printStackTrace();
}
}
}
将其注入您的调度程序
@Service
@EnableScheduling
public class ScheduleUpdatesTransaction {
@Autowired
private ScheduleThreadTransactionService service;
@Scheduled(fixedDelay = 10000)
public void executeTransaction()
{
for(Long key : playerDAO.getUpdatesByTimeIterval(myCustomDateTime))
service.callAsync(key);
}
}
请注意,您可能需要在 spring-conf.xml 中添加更多内容,共享使用 spring 3 + 的配置和 ConcurrentTaskExecutor ,但您可以检查其他实现spring provides ,因为可能有适合您需求的案例。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
">
<context:component-scan base-package = "your.package"/>
<task:annotation-driven executor="taskExecutor" proxy-target-class="false"/>
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ConcurrentTaskExecutor">
<property name="concurrentExecutor" ref="threadPoolExecutor" />
</bean>
<bean id="threadPoolExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" >
<property name="corePoolSize" value="25" />
<property name="maxPoolSize" value="50" />
<property name="queueCapacity" value="100" />
</bean>
</beans>