1. 程式人生 > >Spring使用定時器時無法獲取事務問題

Spring使用定時器時無法獲取事務問題

本人Spring菜鳥,當我使用Springcloud+redis佇列時,我在其中一個模組啟動定時器定時從Redis中取資料更新至資料庫,出現了TransactionRequiredException,解決方ran案是在做更新操作的service層的方法上加上@Transactionl 並新增配置類如下即可完美解決事務問題:

importorg.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean
; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.TransactionManagementConfigurer; import javax.persistence.EntityManagerFactory; /** * Created by JENSEN on 2017/11/15. */ @Configuration public class DataSourceConfig implements TransactionManagementConfigurer { @Value
("${spring.profiles.active}") private String profiles; @Value("${spring.datasource.url}") private String url; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; @Value("${spring.datasource.driverClassName}") private String driverClassName; @Value("${spring.datasource.max-active}") private Integer maxActive; @Value("${spring.datasource.max-idle}") private Integer maxIdle; @Value("${spring.datasource.min-idle}") private Integer minIdle; @Value("${spring.datasource.initial-size}") private Integer initialSize; @Value("${spring.datasource.validation-query}") private String validationQuery; @Value("${spring.datasource.test-on-borrow}") private Boolean testOnBorrow; @Value("${spring.datasource.test-on-return}") private Boolean testOnReturn; @Value("${spring.datasource.test-while-idle}") private Boolean testWhileIdle; @Bean public DataSource dataSource() { DataSource ds = new DataSource(); ds.setUrl(url); ds.setUsername(username); ds.setPassword(password); ds.setDriverClassName(driverClassName); ds.setMaxActive(maxActive); ds.setMinIdle(minIdle); ds.setInitialSize(initialSize); ds.setValidationQuery(validationQuery); ds.setTestOnBorrow(testOnBorrow); ds.setTestOnReturn(testOnReturn); ds.setTestWhileIdle(true); return ds; } @Primary @Bean EntityManagerFactory entityManagerFactory() { LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); emf.setDataSource(dataSource()); emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); emf.setPackagesToScan("com.spring.jensen"); emf.setPersistenceUnitName("default"); emf.afterPropertiesSet(); return emf.getObject(); } @Bean public PlatformTransactionManager transactionManager() { return new JpaTransactionManager(entityManagerFactory()); } @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return null; } }