Spring Batch에서 여러 데이터 소스 사용
Spring Batch 내에서 몇 가지 데이터 소스를 구성하려고 합니다.시작 시 Spring Batch에서 다음 예외를 발생시킵니다.
To use the default BatchConfigurer the context must contain no more thanone DataSource, found 2
배치 구성의 스니펫
@Configuration
@EnableBatchProcessing
public class BatchJobConfiguration {
@Primary
@Bean(name = "baseDatasource")
public DataSource dataSource() {
// first datasource definition here
}
@Bean(name = "secondaryDataSource")
public DataSource dataSource2() {
// second datasource definition here
}
...
}
여러 데이터 소스를 선언하는 Spring 배치에 대한 일부 xml 기반 구성을 보았기 때문에 이 예외가 발생하는 이유를 잘 모르겠습니다.저는 Spring Batch 코어 버전 3.0.1을 사용하고 있습니다.릴리스(Spring Boot 버전 1.1.5 포함).풀어주다.어떤 도움이라도 주시면 대단히 감사하겠습니다.
고유한 배치 구성자를 제공해야 합니다.스프링은 당신을 위해 그 결정을 내리고 싶지 않습니다.
@Configuration
@EnableBatchProcessing
public class BatchConfig {
@Bean
BatchConfigurer configurer(@Qualifier("batchDataSource") DataSource dataSource){
return new DefaultBatchConfigurer(dataSource);
}
...
AbstractBatchConfiguration
먼저 컨테이너에서 검색을 시도합니다. 찾을 수 없는 경우 컨테이너 자체를 생성합니다. 여기서IllegalStateException
용기에 두 개 이상의 콩이 있는 곳에 던져집니다.
문제를 해결하기 위한 접근법은 콩이 만들어지는 것을 막는 것입니다.AbstractBatchConfiguration
우리는 그것을 만들기 위해 힌트를 줍니다.DefaultBatchConfigurer
주석을 사용한 스프링 컨테이너별:
다음에서 파생된 빈 클래스를 포함하는 패키지를 검색하여 주석을 달 수 있는 구성 클래스DefaultBatchConfigurer
:
package batch_config;
...
@EnableBatchProcessing
@ComponentScan(basePackageClasses = MyBatchConfigurer.class)
public class MyBatchConfig {
...
}
빈 파생 클래스의 전체 코드는 다음과 같습니다.
package batch_config.components;
import org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer;
import org.springframework.stereotype.Component;
@Component
public class MyBatchConfigurer extends DefaultBatchConfigurer {
}
이 구성에서 주석은 다음에 대해 작동합니다.DataSource
다음 예와 같이 been:
@Configuration
public class BatchTestDatabaseConfig {
@Bean
@Primary
public DataSource dataSource()
{
return .........;
}
}
이것은 Spring Batch 버전 3.0.3에서 작동합니다.풀어주다
만드는 가장 간단한 해결책@Primary
에 대한 주석.DataSource
작업은 단지 추가하는 것일 수 있습니다.@ComponentScan(basePackageClasses = DefaultBatchConfigurer.class)
와 함께@EnableBatchProcessing
주석:
@Configuration
@EnableBatchProcessing
@ComponentScan(basePackageClasses = DefaultBatchConfigurer.class)
public class MyBatchConfig {
여기서 @vanarchi가 답변한 것과 매우 유사한 솔루션을 제공하고자 합니다. 하지만 필요한 모든 구성을 하나의 클래스에 넣을 수 있었습니다.
완전성을 위해 이 솔루션은 기본 데이터 소스가 hsql이라고 가정합니다.
@Configuration
@EnableBatchProcessing
public class BatchConfiguration extends DefaultBatchConfigurer {
@Bean
@Primary
public DataSource batchDataSource() {
// no need shutdown, EmbeddedDatabaseFactoryBean will take care of this
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase embeddedDatabase = builder
.addScript("classpath:org/springframework/batch/core/schema-drop-hsqldb.sql")
.addScript("classpath:org/springframework/batch/core/schema-hsqldb.sql")
.setType(EmbeddedDatabaseType.HSQL) //.H2 or .DERBY
.build();
return embeddedDatabase;
}
@Override
protected JobRepository createJobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(batchDataSource());
factory.setTransactionManager(transactionManager());
factory.afterPropertiesSet();
return (JobRepository) factory.getObject();
}
private ResourcelessTransactionManager transactionManager() {
return new ResourcelessTransactionManager();
}
//NOTE: the code below is just to provide developer an easy way to access the in-momery hsql datasource, as we configured it to the primary datasource to store batch job related data. Default username : sa, password : ''
@PostConstruct
public void getDbManager(){
DatabaseManagerSwing.main(
new String[] { "--url", "jdbc:hsqldb:mem:testdb", "--user", "sa", "--password", ""});
}
}
이 솔루션의 세 가지 핵심 사항:
- 이 클래스에는 다음과 같은 주석이 있습니다.
@EnableBatchProcessing
그리고.@Configuration
에서 확장되었을 뿐만 아니라DefaultBatchConfigurer
이를 통해 스프링 배치는 다음과 같은 경우 맞춤형 배치 구성업체를 사용하도록 지시합니다.AbstractBatchConfiguration
찾아보려고 합니다.BatchConfigurer
; - 배치 데이터 원본 빈에 다음과 같이 주석 달기
@Primary
이는 스프링클러가 이 데이터 소스를 9개의 작업 관련 테이블을 저장하는 데이터 소스로 사용하도록 지시합니다. - 재정의
protected JobRepository createJobRepository() throws Exception
method - 작업 저장소가 기본 데이터 원본을 사용하고 다른 데이터 원본과 다른 transactionManager 인스턴스를 사용하도록 합니다.
가장 간단한 솔루션은 DefaultBatchConfigurer를 확장하고 한정자를 통해 데이터 소스를 자동 배선하는 것입니다.
@Component
public class MyBatchConfigurer extends DefaultBatchConfigurer {
/**
* Initialize the BatchConfigurer to use the datasource of your choosing
* @param firstDataSource
*/
@Autowired
public MyBatchConfigurer(@Qualifier("firstDataSource") DataSource firstDataSource) {
super(firstDataSource);
}
}
측면 참고(여러 데이터 소스의 사용도 다루기 때문에):자동 구성을 사용하여 데이터 초기화 스크립트를 실행하는 경우 예상되는 데이터 소스에서 초기화되지 않을 수 있습니다.이 문제에 대해서는 다음을 참조하십시오. https://github.com/spring-projects/spring-boot/issues/9528
아래 빈을 정의하고 application.properties 파일에 필요한 항목이 있는지 확인할 수 있습니다.
@Configuration
@PropertySource("classpath:application.properties")
public class DataSourceConfig {
@Primary
@Bean(name = "abcDataSource")
@ConfigurationProperties(prefix = "abc.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
@Bean(name = "xyzDataSource")
@ConfigurationProperties(prefix = "xyz.datasource")
public DataSource xyzDataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
}
application.properties
abc.datasource.jdbc-url=XXXXX
abc.datasource.username=XXXXX
abc.datasource.password=xxxxx
abc.datasource.driver-class-name=org.postgresql.Driver
...........
...........
...........
...........
여기에서 참조할 수 있습니다. 스프링 부팅 두 개의 데이터 소스 구성 및 사용
먼저 사용자 지정 BatchConfigurer를 생성
@Configuration
@Component
public class TwoDataSourcesBatchConfigurer implements BatchConfigurer {
@Autowired
@Qualifier("dataSource1")
DataSource dataSource;
@Override
public JobExplorer getJobExplorer() throws Exception {
...
}
@Override
public JobLauncher getJobLauncher() throws Exception {
...
}
@Override
public JobRepository getJobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
// use the autowired data source
factory.setDataSource(dataSource);
factory.setTransactionManager(getTransactionManager());
factory.afterPropertiesSet();
return factory.getObject();
}
@Override
public PlatformTransactionManager getTransactionManager() throws Exception {
...
}
}
그리고나서,
@Configuration
@EnableBatchProcessing
@ComponentScan("package")
public class JobConfig {
// define job, step, ...
}
언급URL : https://stackoverflow.com/questions/25540502/use-of-multiple-datasources-in-spring-batch
'source' 카테고리의 다른 글
연결이 로컬 호스트인지 자바스크립트로 확인하는 방법은 무엇입니까? (0) | 2023.08.15 |
---|---|
이 바둑 코드에서 SQL 구문 오류 1064가 발생하는 원인은 무엇입니까? (0) | 2023.08.15 |
CSS 필터만 사용하여 검은색을 임의의 색상으로 변환하는 방법 (0) | 2023.08.15 |
어떻게 Tkinter의 이벤트 루프와 함께 자신의 코드를 실행합니까? (0) | 2023.08.15 |
MariaDB / 파일 키 관리 암호화:키 파일에 구문 오류가 발생 (0) | 2023.08.15 |