Spring Batch - не завершается - из-за Stati c Вызов метода - PullRequest
0 голосов
/ 20 июня 2020

Я выполнил пакет Spring (Standalone Jar) в Spring Boot + CommandLineRunner. Но JVM не закрывается после завершения. Проведя небольшое исследование, я сначала подумал, что он не выключается по следующим причинам.

1. Я не закрываю контекст приложения Spring в конце выполнения командной строки. 2. Служба исполнителя не завершается должным образом, что могло вызвать отключение JVM.

Я не хочу вызывать system.exit, который является принудительным завершением работы.

Я попытался закрыть контекст приложения, а также проверенная служба исполнителя завершается с использованием метода isShutdown (возвращает true).

Затем я обнаружил причину root, потому что я вызываю метод stati c, который является виновником. Когда я прокомментировал вызов метода stati c, задание завершилось корректно, даже если я не закрыл контекст приложения явно.

Я не уверен, почему такое поведение, и нужно ли мне преобразовывать все в объекты или Есть что-то еще, чего мне здесь не хватает. Может кто-нибудь пролить свет.

Основной класс

    @SpringBootApplication
@ComponentScan(basePackages = "com.acn.abp.printbatch")
@EnableTransactionManagement
@ImportResource({ "ABPBatchInfrastructure.xml", "financeBillPayAppConfig.xml" })
public class financeBillPayFileUploadApplication extends PrintBatchConstants implements CommandLineRunner {

    @Autowired
    private NotifyConfig notify;

    @Autowired
    private ApplicationContext ctx;

    static final Logger logger = LoggerFactory.getLogger(financeBillPayFileUploadApplication.class);

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(financeBillPayFileUploadApplication.class);

        application.setBannerMode(Banner.Mode.OFF);
        application.run(args);

    }

    @Override
    public void run(String... args) throws Exception {

        logger.info(notify.getEnvironment());

        JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);
        Job job = ctx.getBean(Job.class);

        jobLauncher.run(job,
                new JobParametersBuilder()
                .addString(batchDocumentClass, "InvoiceStatementDocumentation")
                .addString(batchType, "2020-06-04")
                .addString(batchEmailID, notify.getSupportEmailId())
                .addString(batchEnvironment, notify.getEnvironment())
                .toJobParameters());
        
System.out.println("Here cxf");

((ConfigurableApplicationContext)ctx).close();


    }

}

Ниже класса, который вызывает проблему. Если я закомментирую код ниже, все работает отлично.

          populateItemDocuments(job, printConfig.geteCMObjectStore(), printConfig.geteCMUserId());

Файл класса, в котором этот метод называется

@Component
public class DuplexWorker implements Callable {

    static final Logger logger = LoggerFactory.getLogger(DuplexWorker.class);
    @Autowired
    private ManageFormService formgmtClient;
    @Autowired
    private PostScriptService postScriptService;
    @Autowired
    private BarcodeService barcodeService;

    private static CfBatchPrintConfiguration printConfig;
    
    private static CfPersistenceUtil dbUtilService;
    private static FilenetDocumentRetrieval docmgmtClient;

       @Autowired
       public DuplexWorker(CfPersistenceUtil dbUtilService,CfBatchPrintConfiguration printConfig,FilenetDocumentRetrieval docmgmtClient) {
           DuplexWorker.dbUtilService = dbUtilService;
           DuplexWorker.printConfig = printConfig;
           DuplexWorker.docmgmtClient=docmgmtClient;
       }

    
    private MailUtil mailUtil;
    
    private NotifyConfig notify;
    
    private List<PrintJobItem> printJobItems;
    
    private List<String> groupIds;
    
    
    private ArrayList duplexJobs;
    private String groupId;
    private CountDownLatch latch;

    
    public DuplexWorker(ArrayList duplexJobs, String groupId,CountDownLatch latch) {
        super();
        this.latch=latch;
        this.duplexJobs = duplexJobs;
        this.groupId = groupId;
    }
    public DuplexWorker(CountDownLatch latch, MailUtil mailUtil,NotifyConfig notify,List<PrintJobItem> findByPrintStatusEquals,List<String>groupIds) {
        this.latch=latch;
        this.mailUtil=mailUtil;
        this.notify=notify;
        this.printJobItems=findByPrintStatusEquals;
        this.groupIds=groupIds;

    }
    @Override
    public Object call() throws Exception {
        
        try {
        
        if ((duplexJobs != null) && (!duplexJobs.isEmpty())) {
            
              String prevJobId = null;
              int docCount = 0;
              CvPrintJob consolidatedPrintJob = (CvPrintJob)duplexJobs.get(0);

            
              ArrayList printItems = new ArrayList();
              
              if (consolidatedPrintJob != null)
              { 
                  
                  ArrayList items = consolidatedPrintJob.getPrintJobItems();
                  int numPages = 0;
                  if ((items != null) && (!items.isEmpty()))
                  {

                      CvPrintJobItem firstItem = (CvPrintJobItem)items.get(0);
                      
                      numPages = CfBatchPrintUtil.getItemTotalPages(firstItem);
                      logger.info("Item Total Pages == " + numPages);
                      logger.info("Job Item Page Limit == " + 
                        printConfig.getJobItemPageLimit());
                      consolidatedPrintJob.setSequence(firstItem.getSequence());

                  
                }
                  if (numPages <= printConfig.getJobItemPageLimit())
                  {
                    consolidatedPrintJob.setHasLargeItems(false);
                    logger.info("Item setHasLargeItems == false");
                  }
                  else
                  {
                    consolidatedPrintJob.setHasLargeItems(true);
                    logger.info("Item setHasLargeItems == true");
                  }

              }
              
              ArrayList startBannerDataList = new ArrayList();
              ArrayList barcodeList = new ArrayList();
              ArrayList barcodeCorresPageCount = new ArrayList();
              ArrayList statementNumberList = new ArrayList();
              for (int i = 0; i < duplexJobs.size(); i++)
              {
                CvPrintJob job = (CvPrintJob)duplexJobs.get(i);
                if ((prevJobId == null) || 
                  (!prevJobId.equalsIgnoreCase(job.getJobId()))) {
                  docCount = 0;
                }
                
                  populateItemDocuments(job, printConfig.geteCMObjectStore(), printConfig.geteCMUserId());
              }
              
              consolidatedPrintJob.setPrintJobItems(printItems);
              
   }
            else
            {
              logger.info("====================================================================");
              
              logger.info("=================>> No DUPLEX jobs to process <<===================");
              
              logger.info("====================================================================");
            }
            duplexJobs = null;
          
             
            this.latch.countDown();
            System.gc();
                return null;
                
        }catch(Exception e) {
            e.printStackTrace();
            return null;
        }
        
    }
    
      public static void populateItemDocuments(CvPrintJob job, String objectStore, String userid)
                throws CfException
              {
                
                logger.info("Enters populateItemDocuments");
                try
                {
                  ArrayList items = job.getPrintJobItems();
                  job.setIsProcess(true);
                  ArrayList modelDocList = null;
                  logger.info("Items size::::::" + items.size());
                  for (int i = 0; i < items.size(); i++)
                  {
                    modelDocList = new ArrayList();
                    CvPrintJobItem x = (CvPrintJobItem)items.get(i);
                    ArrayList guidList = x.getGuidList();
                    if ((guidList != null) && (!guidList.isEmpty())) {
                      modelDocList.addAll(guidList);
                    }
                    logger.info("guidList size::::::" + guidList.size());
                    
                    CvRenderPayloadRequest cvRenderPayloadRequest = null;
                    if ((modelDocList != null) && (!modelDocList.isEmpty()))
                    {
                      cvRenderPayloadRequest = new CvRenderPayloadRequest();
                      logger.info("Before creating CvRenderPayloadRequest");
                      logger.info("Document Class::: " + 
                        x.getDocumentClass());
                      cvRenderPayloadRequest.setDocumentClass(
                        x.getDocumentClass());
                      cvRenderPayloadRequest.setGuid(modelDocList);
                      cvRenderPayloadRequest.setUserId(userid);
                      logger.info("After creating the CvRenderPayloadRequest");
                      try
                      {
                        if (cvRenderPayloadRequest != null)
                        {
                          List pdfContents = docmgmtClient.retrieveDocument(cvRenderPayloadRequest.getGuid());
                          if ((pdfContents != null) && 
                            (!pdfContents.isEmpty()))
                          {
                            logger.info(
                              "PDF contents sizenew::::::::::::::" + pdfContents.size());
                            Iterator pdfItr = pdfContents.iterator();
                            while (pdfItr.hasNext())
                            {
                              byte[] contents = (byte[])pdfItr.next();
                              
                              CvPrintJobItem item = (CvPrintJobItem)items.get(i);
                              item.addDocumentList(contents);
                              
                              int filenetpagecount = 100;
                              item.setPageCountFromFileNet(filenetpagecount);
                              

                              logger.info("PageCOunt from Filenet " + filenetpagecount);
                            }
                          }
                        }
                      }
                      catch (Exception e)
                      {
                        e.printStackTrace();
                        throw new CfException(" Error populating documents" + e);
                      }
                    }
                  }
                }
                catch (Exception e)
                {
                  e.printStackTrace();
                  throw new CfException(" Error populating documents" + e);
                }
                logger.info("Exits populateItemDocuments");
              }
              

1 Ответ

0 голосов
/ 20 июня 2020

Прежде всего, вы используете сервер Tomcat, на котором выполняется приложение. Если вы хотите создать автономное приложение Spring, вы можете настроить его, как показано ниже:

@Configuration
public class ApplicationMain {

    @Bean
    public Stackoverflow stackoverflow() {
        return new Stackoverflow ();
    }

    public static void main(String[] args) {
        ConfigurableApplicationContext configurableApplicationContext = new AnnotationConfigApplicationContext(ApplicationMain.class);
        System.out.println(configurableApplicationContext.getBean("stackoverflow"));
    }
}

«JVM не завершает работу после завершения». это нормальное поведение для сервера Tomcat, потому что он ожидает обработки запроса.

Вы можете указать базовый пакет, как показано ниже

new AnnotationConfigApplicationContext("com.example");

он просканирует пакет для вас

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...