当前位置: 首页 > 知识库问答 >
问题:

Java-Spring-Batch和Quartz以及Tomcat--返回工作bean的缓存实例

姜弘新
2023-03-14
2016-03-09 11:20:00,047  INFO org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-1   RunFirstBatch.run  111 : RunFirstBatch().run() - Starting.................................[]
2016-03-09 11:20:00,047  INFO org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-1   RunFirstBatch.run  112 : RunFirstBatch().run() - CWD......................................[C:\Users\n0002501\AppData\Local\CI Eclipse for Java EE]

...removed for brevity...

2016-03-09 11:20:03,880  INFO org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-1   FirstBatch.execute  113 : FirstBatch().execute().................................................[** First Batch Job is Executing! **]
2016-03-09 11:20:03,880  INFO org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-1   FirstBatch.execute  114 : FirstBatch().execute() Step Contribution...............................[[StepContribution: read=0, written=0, filtered=0, readSkips=0, writeSkips=0, processSkips=0, exitStatus=EXECUTING]]
2016-03-09 11:20:03,880  INFO org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-1   FirstBatch.execute  115 : FirstBatch().execute() Chunk Context...................................[ChunkContext: attributes=[], complete=false, stepContext=SynchronizedAttributeAccessor: [], stepExecutionContext={batch.stepType=org.springframework.batch.core.step.tasklet.TaskletStep, batch.taskletType=com.lmig.batch.FirstBatch}, jobExecutionContext={}, jobParameters={}]

...removed for brevity...

2016-03-09 11:20:05,542  INFO org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-1   SimpleJobLauncher.run  136 : Job: [FlowJob: [name=firstBatchJob]] completed with the following parameters: [{}] and the following status: [COMPLETED]
2016-03-09 11:20:05,542  INFO org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-1   RunFirstBatch.run  126 : RunFirstBatch().run() - Exit Status..............................[COMPLETED]
2016-03-09 11:20:05,542  INFO org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-1   RunFirstBatch.run  145 : RunFirstBatch().run()............................................[finally]
2016-03-09 11:21:00,008  INFO org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-2   RunFirstBatch.run  111 : RunFirstBatch().run() - Starting.................................[]
2016-03-09 11:21:00,008  INFO org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-2   RunFirstBatch.run  112 : RunFirstBatch().run() - CWD......................................[C:\Users\n0002501\AppData\Local\CI Eclipse for Java EE]

...removed for brevity...

...Returning cached instance of singleton bean 'firstBatchJob'

...removed for brevity...

2016-03-09 11:21:01,730  INFO org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-2   SimpleStepHandler.shouldStart  217 : Step already complete or not restartable, so no action to execute: StepExecution: id=1, version=3, name=stepOne, status=COMPLETED, exitStatus=COMPLETED, readCount=0, filterCount=0, writeCount=0 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=1, rollbackCount=0, exitDescription=
2016-03-09 11:21:01,730 DEBUG org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-2   SimpleFlow.resume  178 : Completed state=firstBatchJob.stepOne with status=COMPLETED
2016-03-09 11:21:01,730 DEBUG org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-2   SimpleFlow.resume  164 : Handling state=firstBatchJob.end1
2016-03-09 11:21:01,730 DEBUG org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-2   SimpleFlow.resume  178 : Completed state=firstBatchJob.end1 with status=COMPLETED
2016-03-09 11:21:01,730 DEBUG org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-2   AbstractJob.execute  305 : Job execution complete: JobExecution: id=1, version=1, startTime=Wed Mar 09 11:21:00 EST 2016, endTime=null, lastUpdated=Wed Mar 09 11:21:00 EST 2016, status=COMPLETED, exitStatus=exitCode=COMPLETED;exitDescription=, job=[JobInstance: id=0, version=0, Job=[firstBatchJob]], jobParameters=[{}]

...removed for brevity...

2016-03-09 11:21:02,050  INFO org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-2   SimpleJobLauncher.run  136 : Job: [FlowJob: [name=firstBatchJob]] completed with the following parameters: [{}] and the following status: [COMPLETED]
2016-03-09 11:21:02,050  INFO org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-2   RunFirstBatch.run  126 : RunFirstBatch().run() - Exit Status..............................[COMPLETED]
2016-03-09 11:21:02,050  INFO org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-2   RunFirstBatch.run  145 : RunFirstBatch().run()............................................[finally]

我试过的事情:

  • scope=“prototype”
  • restartable=“true”
  • 实现了一个ApplicationContextAware类来获取ApplicationContext。
  • 为beforeJob()和afterJob()实现了一个JobExecutionListener类。

以下是细节:

<bean id="batchApplicationContext" class="com.lmig.cm.rore.refmigrator.BatchApplicationContextProvider" scope="singleton"/>    

<bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
    <property name="transactionManager" ref="transactionManager"/>
</bean>

<bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher" scope="prototype">
    <property name="jobRepository" ref="jobRepository" />
</bean>

<bean id="firstBatch" class="com.lmig.batch.FirstBatch" scope="prototype"/>
<batch:step id="firstBatchStepOne">
    <batch:tasklet ref="firstBatch"/>
</batch:step>
<batch:job id="firstBatchJob" restartable="true">
    <batch:step id="stepOne" parent="firstBatchStepOne"/>
</batch:job>

<bean id="runFirstBatch" class="com.lmig.cm.rore.refmigrator.RunFirstBatch">
    <property name="context" ref="batchApplicationContext" />
</bean> 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;

public class RunFirstBatch {

    public static final String ID              = RunFirstBatch.class.getName ();
    private String             SHORT_NAME      = "RunFirstBatch()";
    @SuppressWarnings("unused")
    private String                  SYSTEM_IDENTITY = String.valueOf ( System.identityHashCode ( this ) );

    private     Log                 log = LogFactory.getLog(RunFirstBatch.class.getName());

    //private     ApplicationContext  context = null;
    private     BatchApplicationContextProvider context;

    /**
     * Default constructor.
     */
    public RunFirstBatch() {
        this.context = new BatchApplicationContextProvider();
    }

    public  void    run() { 

        try { 
            getLog().info ( SHORT_NAME + ".run() - Starting.................................[" + "]" );
            getLog().info ( SHORT_NAME + ".run() - CWD......................................[" + System.getProperty ( "user.dir" ) + "]" );

            //context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
            //this.context = new ClassPathXmlApplicationContext("/RoreWebConfiguration.xml");

            //String[] springConfig  = {"/first-batch.xml"};
            //context = new ClassPathXmlApplicationContext ( springConfig );

            if ( getContext() != null ) { 
                if ( getContext().getApplicationContext () != null ) { 
                    JobLauncher jobLauncher = (JobLauncher)getContext().getApplicationContext ().getBean("jobLauncher");
                    Job job = (Job) getContext().getApplicationContext ().getBean("firstBatchJob");
                    JobExecution execution = jobLauncher.run ( job, new JobParameters() );
                    //jobLauncher.run ( job, new JobParameters() );
                    getLog().info ( SHORT_NAME + ".run() - Exit Status..............................[" + execution.getStatus () + "]" );
                }
                else { 
                    getLog().info ( SHORT_NAME + ".run() - ApplicationContext is NULL...............[NULL]" );

                }
            }
            else { 
                getLog().info ( SHORT_NAME + ".run() - BatchApplicationContext is NULL..........[NULL]" );

            }

        }
        catch ( Exception ltheXcp ) { 
            getLog().error ( SHORT_NAME + ".run() - Exception ...............................[" + ltheXcp.getMessage () + "]" );
            getLog().error ( ltheXcp );

        }
        finally { 
            getLog().info ( SHORT_NAME + ".run()............................................[finally]" );
            //if (context != null) {
            //    context = null;
            //}

        }
    }

    public Log getLog() {
        return log;
    }

    public void setLog(Log log) {
        this.log = log;
    }

    public BatchApplicationContextProvider getContext() {
        return context;
    }

    public void setContext(BatchApplicationContextProvider context) {
        this.context = context;
    }


}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;

import com.lmig.cm.rore.refmigrator.CMRoreReferenceMigrator;

public class FirstBatch implements Tasklet {

    public static final String ID              = FirstBatch.class.getName ();
    private String             SHORT_NAME      = "FirstBatch()";
    @SuppressWarnings("unused")
    private String              SYSTEM_IDENTITY = String.valueOf ( System.identityHashCode ( this ) );

    private     Log             log = LogFactory.getLog(FirstBatch.class.getName());

    public FirstBatch() {
        // TODO Auto-generated constructor stub
    }

    public FirstBatch( Log theLog ) {
        this.log = theLog;
    }

    /* (non-Javadoc)
     * @see org.springframework.batch.core.step.tasklet.Tasklet#execute(org.springframework.batch.core.StepContribution, org.springframework.batch.core.scope.context.ChunkContext)
     */
    @Override
    public RepeatStatus execute(StepContribution arg0, ChunkContext arg1)
        throws Exception {
        getLog().info(SHORT_NAME + ".execute().................................................[** First Batch Job is Executing! **]");
        getLog().info(SHORT_NAME + ".execute() Step Contribution...............................[" + arg0.toString () + "]");
        getLog().info(SHORT_NAME + ".execute() Chunk Context...................................[" + arg1.toString () + "]");
        return RepeatStatus.FINISHED;
        //return RepeatStatus.CONTINUABLE;

    }

    public Log getLog() {
        return log;
    }

    public void setLog(Log log) {
        this.log = log;
    }


}
    null

解决方案是简单地在JobParameters()中提供至少一个JobParameter,它允许Spring-Batch“唯一地”标识一个JobInstance与另一个JobInstance。我只是使用了当前日期/时间作为字符串:

在runFirstBatch.run()方法中添加以下代码

        SimpleDateFormat    theFormat = new SimpleDateFormat ( "yyyy-MM-dd-HH-mm-ss" );

        if ( getBatchContext ().getApplicationContext () != null ) { 
            if ( getBatchContext ().getApplicationContext () != null ) { 
                JobLauncher     jobLauncher = (JobLauncher)getBatchContext ().getApplicationContext ().getBean("jobLauncher");
                Job             job = (Job) getBatchContext ().getApplicationContext ().getBean("firstBatchJob");

                // JOBPARAMETERS : Build the job parameters...
                // 
                Date            theDate = new Date();
                // format the date as yyyy-MM-dd-HH-mm-ss 
                String          theJobId = theFormat.format ( theDate );
                // job parameter (single) from the formatted date...
                JobParameter    idParm = new JobParameter ( theJobId );
                // parameters container...used for the JobParameters
                // constructor...
                Map<String,JobParameter> mapParms = new HashMap<String,JobParameter> ();
                mapParms.put ( "1", idParm );

                JobParameters   theParms = new JobParameters (mapParms);

                getLog().info ( SHORT_NAME + ".run() - Job Id...................................[" + theJobId + "]" );


                JobExecution    execution = jobLauncher.run ( job, theParms );
                //execution.setExitStatus ( ExitStatus.UNKNOWN );
                //jobLauncher.run ( job, new JobParameters() );
                getLog().info ( SHORT_NAME + ".run() - Exit Status..............................[" + execution.getStatus () + "]" );
            }
            else { 
                getLog().info ( SHORT_NAME + ".run() - ApplicationContext is NULL...............[NULL]" );

            }
        }
        else { 
            getLog().info ( SHORT_NAME + ".run() - BatchApplicationContext is NULL..........[NULL]" );

        }

共有1个答案

羊舌炯
2023-03-14

保留repeatstatus.finished但查看https://docs.spring.io/spring-batch/reference/html/domain.html#domainjobparameters

“一个工作岗位与另一个工作岗位有什么区别?”答案是:JobParameters。JobParameters是一组用于启动批处理作业的参数。

 类似资料:
  • 问题内容: 有没有人有很好的Spring Batch(使用批注)示例来缓存可供处理器访问的参考表? 我只需要一个简单的缓存,运行一个查询,该查询返回一些byte []并将其保留在内存中,直到执行作业。 感谢有关此主题的任何帮助。 谢谢 ! 问题答案: 可以使用A 在执行作业之前用参考数据填充高速缓存,并在作业完成后清除高速缓存。 这是一个例子: 执行后,将打印: 这意味着可以从缓存中正确检索数据。

  • 我一直在使用Spring Cache抽象和ehCache。我在目标方法上使用@Cacheable注释,如下所示: 注意:如果我没有在@cacheable注释中指定“key”,那么它可以工作。 有什么我忘了说明的吗?配置?注释?

  • 我试图使用Spring batch Java配置和Quartz作为调度程序来编写一个批处理作业。 我可以探索的所有示例都通过扩展QuartzJobBean创建了自己的作业类,但我希望上面配置的作业被调度运行。 如何对调度程序功能进行单元测试。

  • 以下SpringBean声明似乎“按预期”运行和行为: 其中“如预期”表示“没有明显的错误”。 假设有一些复杂的生命周期(例如,使用管理外部资源),这是的有效且合理的声明吗?我能找到的所有示例(官方和非官方)都表明实例应该在中实例化,而不是存储在字段中或从字段中检索。然而,我在任何文件中都找不到任何确定的信息,说明这应该或不应该是安全的。 例如,我能找到的最相关的文档是关于SpringIoCbea

  • 我想将主数据缓存到Redis。 所以,我写了这些代码。 和 和ymlfile 但是,缓存不工作... 无论何时调用printTest方法,都将执行“getTest”方法。Redis没有数据。。。我的代码中有什么问题? SpringBoot版本是1.4.0 依赖关系是

  • 本文向大家介绍Spring整合Quartz Job以及Spring Task的实现方法,包括了Spring整合Quartz Job以及Spring Task的实现方法的使用技巧和注意事项,需要的朋友参考一下 Spring中常用的定时任务的主要有两种 1、Spring整合Quartz Job 2、Spring 3.0以后自带的Task 一、两种定时任务的实现方式 Quartz job 1、首先编写任