CSV -потоковая передача в Java выходит из строя с слишком большой полезной нагрузкойJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 CSV -потоковая передача в Java выходит из строя с слишком большой полезной нагрузкой

Сообщение Anonymous »

Реализованный потоковой CSV -файл в Java Spring Boot. Текущий шлюз имеет предел отклика 10 МБ. Реализация потоковой передачи выполнена для обхода предела 10 МБ шлюза < /p>
try (CSVPrinter csvPrinter = new CSVPrinter(response.getWriter(), CSVFormat.DEFAULT.withHeader(headers))) {
// Get PIT ID with 5 minute keep-alive - system will cache and reuse if already available
String pitId = openSearchClient.createPITId(worktypeCode, "5m");
String[] searchAfter = null;

// Build query for filtering
BoolQueryBuilder query = buildQueryForTaskSearch(taskStatuses, worklistIds, filter);
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(query)
.build();

logger.info("Starting CSV export for worktype {} with batch size {}", worktypeCode, batchSize);

// Get the tenant name for index prefix
String tenantName = TenantThreadUtil.getTenantDetails().get(TenantConstants.TENANT_NAME);
String indexPrefix = tenantName + "_" + worktypeCode;

// Paginate through all results using PIT and search_after
int recordsInCurrentOsBatch = 0; // Counter for flushing
final int FLUSH_INTERVAL = 100; // Flush after every 100 records, for example

while (true) {
// Get a batch of results using PIT
JSONObject searchResponse = openSearchClient.searchWithPIT(worktypeCode, pitId, batchSize, searchAfter, searchQuery);
JSONObject hitsObject = searchResponse.getJSONObject("hits");
JSONArray hits = hitsObject.getJSONArray("hits");

if (hits.length() == 0) {
break; // No more results
}

// Process each hit and write to CSV
for (int i = 0; i < hits.length(); i++) {
JSONObject hit = hits.getJSONObject(i);
JSONObject source = hit.getJSONObject("_source");

// Convert source to Task object first using the transformer
Task task = transformer.entityConverter(source, indexPrefix);

if (task != null) {
// Use extractCsvValues method compatible with TaskSearchService
String[] values = extractCsvValues(task, fieldMappings);

// Write record to CSV
csvPrinter.printRecord((Object[])values);
processedResults++;
recordsInCurrentOsBatch++;

// Flush after each record to mimic Node.js line-by-line sending
csvPrinter.flush();

// Check if max limit reached for the entire response
if (maxLimit > 0 && processedResults >= maxLimit) {
logger.info("Reached max limit of {} records for CSV export", maxLimit);
return;
}
}

// Check if flush interval reached
if (recordsInCurrentOsBatch % FLUSH_INTERVAL == 0) {
try {
csvPrinter.flush();
} catch (java.io.IOException e) {
// Client might have closed connection, log and potentially stop
logger.warn("IOException during periodic flush: {}", e.getMessage());
// Depending on desired behavior, you might re-throw, break, or return
throw e; // For now, re-throw to ensure visibility
}
< /code>
Но приведенная ниже реализация в node.js работает < /p>
let csvContentsToDownload =
csvStringifier.getHeaderString() +
csvStringifier.stringifyRecords(allTasksData);
res.setHeader('Content-disposition', 'attachment; filename=AllDownload.csv');
res.set('Content-Type', 'text/csv');
// Write to express response stream to avoid hitting gateway limit of 10 MB
csvContentsToDownload.split('\n').forEach(substr => res.write(substr + '\n'));
res.status(200).end();
< /code>
Я установил аналогичные заголовки для реализации Java. Java
Он работает нормально в локальном, потому что нет ограничения шлюза.
и конфигурация шлюза одинаковы для обоих служб.>

Подробнее здесь: https://stackoverflow.com/questions/796 ... -too-large
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»