有几个示例说明我们如何在不将元数据持久化到数据库的情况下使用 Spring Batch。以下是有关此事的一些示例和相关问题:
但是我有一个稍微不同的用例:我有一些工作每小时运行一次,我想将元数据保存到我的数据库中(例如,创建报告,运行一些测试,这两者在处理过程中可能有点繁重)。我有一些其他类型的作业每分钟左右运行一次(例如,解锁由于重复输入错误密码而被锁定的用户帐户等),它们不涉及太多处理,而是一个简单的 sql 查询。
这里的问题分为两部分:
@Scheduled
的方法吗?注释就够了吗? 最佳答案
- Is there a way to keep metadata of the first type of jobs (e.g. reports processing) in the database while not using database persistence at all for second type of jobs (e.g. unlocking user accounts)?
这是配置问题。您可以使用 Spring profiles对于数据源。这个想法是定义一个持久数据源和一个内存中的数据源。然后像往常一样使用数据源配置所有作业,并在运行时使用正确的配置文件运行它们。这是一个快速示例:
import javax.sql.DataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
@Configuration
@EnableBatchProcessing
public class JobsConfiguration {
@Bean
public Job job1() {
return null;
}
@Bean
public Job job2() {
return null;
}
@Bean
@Profile("in-memory")
public DataSource embeddedDataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript("/org/springframework/batch/core/schema-hsqldb.sql")
.build();
}
@Bean
@Profile("persistent")
public DataSource persistentDataSource() {
HikariDataSource hikariDataSource = new HikariDataSource();
// TODO configure datasource
return hikariDataSource;
}
}
如果您使用
-Dspring.profiles.active=in-memory
运行您的应用程序,在您的应用程序上下文中将只有嵌入的数据源 bean,它将由 @EnableBatchProcessing
自动配置的作业存储库使用。 .
- Or, would even using Spring Batch for second type of jobs be overkill/not needed at all? Simply a method with @Scheduled annotation would be enough?
which do not involve much of processing but a simple sql query
: 如果是简单的 sql 查询,并且不需要持久化元数据,那么使用带有 @Scheduled
注释的方法可能会更好使用 jdbcTemplate
运行查询。
关于spring - 有没有办法跳过仅针对特定作业的 Spring Batch 持久元数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58536721/