Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring计划线程未访问数据库_Java_Multithreading_Spring_Jpa_Scheduled Tasks - Fatal编程技术网

Java Spring计划线程未访问数据库

Java Spring计划线程未访问数据库,java,multithreading,spring,jpa,scheduled-tasks,Java,Multithreading,Spring,Jpa,Scheduled Tasks,我试图实现的是每30分钟安排一次对数据库的查询,此查询将为我带来许多记录,其中包含许多要安排的新任务,这些新任务将对我的数据库执行新的CRUD操作和一些其他操作 首先,我使用@EnableScheduling来安排一个“SELECT”查询 问题是调用findOne时,我得到NullPointerException。有什么建议吗?我正在使用Spring4和JPA2.1 编辑: 我在配置中做了一些更改,这是我的XML配置: <context:component-scan base-packag

我试图实现的是每30分钟安排一次对数据库的查询,此查询将为我带来许多记录,其中包含许多要安排的新任务,这些新任务将对我的数据库执行新的CRUD操作和一些其他操作

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

问题是调用findOne时,我得到NullPointerException。有什么建议吗?我正在使用Spring4和JPA2.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" />
添加@Transactional时,请告诉我此错误:

2015-09-28 12:33:32840 scheduledExecutorFactoryBean-1 ERROR service.StatusUpdateService-org.springframework.beans.factory.NoSuchBeanDefinitionException:找不到依赖项类型为[com.myproject.ScheduleThreadTransactionService]的符合条件的bean:应至少有一个符合此依赖项autowire候选项条件的bean。依赖项注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

有没有一个简短的修复程序来运行这个东西


注意。

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

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

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

在ScheduleThreadTransaction类中进行以下更改

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

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

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

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

在ScheduleThreadTransaction类中进行以下更改

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

您没有以正确的方式注入Springbean,但是您正在使用new创建引用,因此它不是上下文感知的Springbean,因此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中添加更多内容,与ConcurrentTaskExecutor共享使用spring 3+的配置,但您可以检查其他实现,因为可能存在适合您需要的情况

<?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>

您没有以正确的方式注入Springbean,但是您正在使用new创建引用,因此它不是上下文感知的Springbean,因此DAO为空,但是因为您已经在使用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中添加更多内容,与ConcurrentTaskExecutor共享使用spring 3+的配置,但您可以检查其他实现,因为可能存在适合您需要的情况

<?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>


什么是空值?标识符还是dao?PlayerTaskDAO类什么是空的?标识符还是dao?PlayerTaskDAO classInjecting runnableFactory成功了,问题是我只能执行SELECT查询,我不能修改我的数据,因为抛出了“无事务EntityManager可用异常”,将@transactional添加到我的方法中会抛出“无类型的限定bean”。我需要手动处理交易吗?那完全是另一个问题。您需要研究如何配置spring事务。如果run()中有多个crud操作,那么最好定义一个由接口支持的服务类,该接口具有调用多个dao操作的方法。将这些方法标记为事务性方法并注入此服务,而不是playerDAO…..***由于上面的答案解决了您的原始问题,请将其标记为right/upvote.****是的,我使用的是:注入runnableFactory成功了,问题是我只能执行SELECT查询,我无法修改我的数据,因为引发了“No transactional EntityManager available exception”(无事务性EntityManager可用异常),将@Transactional添加到我的方法中会抛出“没有类型的限定bean”。我需要手动处理交易吗?那完全是另一个问题。您需要研究如何配置spring事务。如果run()中有多个crud操作,那么最好定义一个由接口支持的服务类,该接口具有调用多个dao操作的方法。将这些方法标记为事务性方法并注入此服务,而不是playerDAO…..***因为上面的答案解决了您的原始问题,请将其标记为right/upvote.****是的,我使用这个:使用@Async允许我在数据库中执行更新?触发时间可以通过编程方式进行参数化?是的,您可以在执行后使用它,
@Service
@EnableScheduling
public class ScheduleUpdatesTransaction {

    @Autowired
    private ScheduleThreadTransactionService service;

    @Scheduled(fixedDelay = 10000)
    public void executeTransaction() 
    {
       for(Long key : playerDAO.getUpdatesByTimeIterval(myCustomDateTime))
          service.callAsync(key);
    }
}
<?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>