Spring计划的线程不访问数据库

时间:2015-08-18 07:02:46

标签: java multithreading spring jpa scheduled-tasks

我想要实现的是每30分钟为我的数据库安排一次查询,这个查询会给我带来许多记录,其中有许多新任务要安排,这些新任务将对我的数据库和其他一些操作执行新的CRUD操作。

首先,我正在使用@EnableScheduling来安排“SELECT”查询

<table class="forum_view_topic_table"> 
    <tr calss="view_topic_th">
            <th class="view_topic_th_left" align="right">Date</th> 
            <th class="view_topic_th_right">Count</th> 
        </tr>
    <tr>
        <td width='200' valign='top' align='center' style='border: 1px solid #000000;'>User Info Here!</td>
        <td valign='top' style='border: 1px solid #000000'>
            <div style='min-height: 125px;'>Post 1
                <br />by John Smith
                <hr />Content</div>
        </td>
    </tr>
    <tr>
        <td colspan='2'>
            <hr />
        </td>
    </tr>
    <?php } ?>
</table>

这是ScheduleThreadTransaction类:

@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();
    }
}

问题是当调用 findOne 时,我得到 NullPointerException 。有什么建议吗?我正在使用Spring 4和JPA 2.1。

修改

我在配置中做了一些变化,这是我的XML配置:

@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;
    }

}

这是ScheduleUpdatesTransaction类:

<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" />

StatusUpdateService类:

@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);   
        }
    }
}

最后是ScheduleThreadTransactionService类:

@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);
        }
    }

}

添加@Transactional会给我这个错误:

2015-09-28 12:33:32,840 scheduledExecutorFactoryBean-1 ERROR service.StatusUpdateService - org.springframework.beans.factory.NoSuchBeanDefinitionException:找不到[com.myproject.ScheduleThreadTransactionService]类型的限定bean用于依赖:至少预期1个bean,有资格作为此依赖项的autowire候选者。依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

是否有一个简短的方法可以让这个东西运行?

问候。

2 个答案:

答案 0 :(得分:0)

您正在使用new来实例化可运行的spring组件。如果要手动实例化,Spring容器将无法注入依赖项。

您需要从bean工厂获取runnable的实例。更简洁的方法是使用工厂和查找方法注入。

如果所有的spring配置都使用注释,那么等效的查找方法将是

在你的sheduleThreadTransaction类中进行以下更改

List<Region> regions = regionRepository.GetAll().ToList();

并在executeTransaction方法中

@Autowired
  private javax.inject.Provider<ScheduleThreadTransaction> runnableFactory;

答案 1 :(得分:0)

你没有以正确的方式注入spring bean但是你正在用new创建引用,因此它不是一个上下文感知的spring bean,所以DAO是null,但是因为你已经在使用调度/ Spring提供的异步,您可以创建一个单例bean,使用您想要的方法并将所有DAO和人员注入其中,并通过调度程序将该方法称为async,这样您就可以避免使用自己的线程执行程序创建相应的线程让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>