reports-service запуск в режиме сервиса и в режиме утилиты

This commit is contained in:
AKurakin 2023-01-11 11:21:56 +03:00
parent e1a73ad82a
commit 371e22eee4
5 changed files with 111 additions and 12 deletions

35
clearing-parent/readme.md Normal file
View file

@ -0,0 +1,35 @@
report-service
==============
Сервис для генерации отчётов.
Формат xml, docx.
Параметры запуска
-----------------
--spring.config.location= путь к папке с файлом настроек application.properties
--console - признак, что надо запуститься не как сервис, слушающий очередь kafka, а как утилита для генерации отчётов за текущий день/месяц и выключиться.
Пример:
java -jar report-service.jar --spring.config.location=clearing/clearing-parent/reports-service/src/main/resources/ --console
Настройки
---------
В файле application.properties настройки:
reports-service.hazelcast.cluster-members=ip адрес(а) кластера imdg, например: 127.0.0.1:5701
reports-service.hazelcast.login=логин доступа к кластеру
reports-service.hazelcast.password=пароль доступа к кластеру
reports-service.ReportModuleOut=./report_out - путь к папке для генерации отчётов
reports-service.kafka-consumer - группа настроек для подключения к очереди kafka
и другие настройки.

View file

@ -9,7 +9,9 @@ import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import ru.spcex.clearing.reports.config.ReportCmdParser;
import ru.spcex.clearing.reports.reports.bt_16_5.ReportINACCNT;
import ru.spcex.clearing.reports.services.QCommandExecutor;
import ru.spcex.clearing.reports.services.ReportsServiceCommand;
import ru.spcex.clearing.reports.services.collector.ReportINACCNT_Collector;
import ru.spcex.platform.imdg.api.ImdgProvider;
@ -18,26 +20,37 @@ import ru.spcex.platform.imdg.api.ImdgProvider;
public class ReportsServiceApplication {
public static void main(String[] args) {
try {
ReportCmdParser cmdArgs = new ReportCmdParser(args);
SpringApplicationBuilder builder = new SpringApplicationBuilder(ReportsServiceApplication.class);
builder.run(args);
ConfigurableApplicationContext context = builder.run(args);
test(context);
//todo это тест. Переписать код с учётом параметров запуска - как сервис или разово все из командной строки.
ReportsServiceCommand reportCommand = context.getBean(ReportsServiceCommand.class);
reportCommand.writeAllXML();
// Logger log = LoggerFactory.getLogger(ReportsServiceApplication.class);
// log.info("Shutdown application after work");
// context.close(); // todo если будет запущен как сервис, сделать выход опционально, по другому.
Logger log = LoggerFactory.getLogger(ReportsServiceApplication.class);
if (cmdArgs.isConsole()) {
log.info("Console mode");
try {
ReportsServiceCommand reportCommand = context.getBean(ReportsServiceCommand.class);
reportCommand.writeAllXML();
} finally {
log.info("Shutdown application after work");
context.close();
}
} else {
log.info("Service mode");
QCommandExecutor queueListener = context.getBean(QCommandExecutor.class);
log.trace("QCommandExecutor: {}", queueListener);
}
} catch (Throwable e) {
LoggerFactory.getLogger(ReportsServiceApplication.class).error("Report-service start failed: {} -> {}", e.getClass().getSimpleName(), ExceptionUtils.getStackTrace(e));
System.exit(-1);
}
// ReportsService reportsService = new ReportsService();
// reportsService.writeXML();
}
/* для тестирования:
ReportsService reportsService = new ReportsService();
reportsService.writeXML();
test(context);
@Deprecated
public static void test(ConfigurableApplicationContext context) {
ImdgProvider imdg = context.getBean(ImdgProvider.class);
@ -48,4 +61,5 @@ public class ReportsServiceApplication {
String out = xStream.toXML(report);
System.out.println(out);
}
*/
}

View file

@ -0,0 +1,43 @@
package ru.spcex.clearing.reports.config;
/**
* Параметры запуска командной строки.
*
* @see ru.spcex.clearing.reports.config.element.ReportsServiceSettings
*/
public class ReportCmdParser {
protected static final String ARG_CONSOLE = "--console";
protected static final String ARG_SERVICE = "--service";
protected boolean console;
protected boolean service;
public ReportCmdParser(String[] args) {
for (String arg : args) {
if (ARG_CONSOLE.equals(arg)) console = true;
if (ARG_SERVICE.equals(arg)) service = true;
}
}
public boolean isConsole() {
return console;
}
public boolean isService() {
return service;
}
@Override
public String toString() {
return "ReportCmdParser{console=" + console + ", service=" + service + '}';
}
}
/*
Вариант парсинга сложных выражений:
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.4</version>
</dependency>
но сейчас достаточно один параметр проверять
*/

View file

@ -5,6 +5,8 @@ import org.apache.kafka.clients.consumer.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import ru.spcex.clearing.platform.messaging.domain.BaseRequest;
import ru.spcex.clearing.platform.messaging.domain.cud.reports.ReportWithPeriodRequest;
import ru.spcex.clearing.platform.messaging.service.QueueConsumer;
@ -17,6 +19,8 @@ import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
@Service
@Lazy // требуется получать экземпляр сервиса явно, когда надо его запустить
public class QCommandExecutor extends QueueConsumer implements InitializingBean {
private static final String QUEUE_RUN_REPORT_COMMAND = "GREP"; // см. Task.createReport
private final Logger log = LoggerFactory.getLogger(getClass());
@ -37,7 +41,7 @@ public class QCommandExecutor extends QueueConsumer implements InitializingBean
@Override
public void afterPropertiesSet() {
log.debug("Init queue listener {}", getClass().getSimpleName());
log.info("Init queue listener {}", getClass().getSimpleName());
callback(ReportWithPeriodRequest.class)
.setConsumer(this::newReportWithPeriod)
.forDestination(Task.createReport.topic(), callbacks::put);

View file

@ -106,6 +106,9 @@ public class ReportsServiceCommand implements InitializingBean {
File outPath = new File(settings.getReportModuleOut());
XMLReportBuilder reportBuilder = new XMLReportBuilder(reportDataCollector.getReportClass(), outPath);
AbstractReport report = reportDataCollector.collectReportWithPeriod(startDate, endDate);
if (report == null) {
throw new NullPointerException("reportDataCollector "+ reportDataCollector +" return null");
}
File reportFile = reportBuilder.createReport(report);
if (reportFile != null) {
log.debug("New report file done: \"{}\"", reportFile);