Spring Boot: версии 3.2.6 - 3.4.6 < /li>
< /ul>
У меня есть следующий контроллер и служба: < /p>
Код: Выделить всё
@RequiredArgsConstructor
@RestController
public class MyEntityController {
private final MyEntityService service;
@PostMapping("/file")
public ResponseEntity addedFileInVersion(MultipartHttpServletRequest request) throws IOException {
return service.addFileVersion(request);
}
}
@Service
@Slf4j
@RequiredArgsConstructor
public class MyEntityService {
@Transactional
public ResponseEntity addFileVersion(MultipartHttpServletRequest request) throws IOException {
try {
log.info("Before reading : {} bytes", getDirectMemoryUsed());
MultipartFile file = request.getFile("file");
if (file == null) {
return ResponseEntity.badRequest().body("The file has not been transferred or the file is empty.");
}
byte[] array = file.getBytes();
String fileName = file.getOriginalFilename();
storeFile(array, fileName);
log.info("After reading : {} bytes", getDirectMemoryUsed());
return ResponseEntity.ok("ok");
} catch (IOException e) {
log.error("Error processing file", e);
return ResponseEntity.badRequest().body("Error when uploading file: " + e.GetMessage());
} finally {
log.info("Finally reading : {} bytes", getDirectMemoryUsed());
}
}
private void storeFile(byte[] array, String path) throws IOException {
String decode = UriUtils.decode(path, StandardCharsets.UTF_8.toString());
synchronized (this) {
Path savedPath = Paths.get("/storage/tmp", decode);
if (Files.notExists(savedPath.getParent())) {
Files.createDirectories(savedPath.getParent());
}
Files.write(savedPath, array);
}
}
private double getDirectMemoryUsed() {
List bufferPoolMXBeans = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
for (BufferPoolMXBean pool : bufferPoolMXBeans) {
if ("direct".equals(pool.getName())) {
return pool.getMemoryUsed();
}
}
return 0;
}
}
< /code>
При отправке файлов я наблюдаю за увеличением использования прямой памяти, которая не уменьшается после обработки файла. Журналы показывают следующее: < /p>
step < /th>
< /th>
< /tr>
< /thaed>
< /tr>
< /thead>
< /tr>
< /th>
< /tr>
< /th>
< /tr>
< /th>
< /tr>
< /th> /> перед чтением < /td>
24576.0 Bytes < /td>
< /tr>
Наконец -то чтение < /td>
9.58496462e8 bytes < /td>
< /tr>
Чтение < /td>
9.58496462e8 Bytes < /td>
< /tr>
перед чтением < /td>
. reading
1.916984732E9 bytes
Finally reading
1.916984732E9 bytes
Можно видеть, что после обработки файла прямая память не выпускается.
Я понимаю, что использование file.getbytes () Подробнее здесь: https://stackoverflow.com/questions/797 ... ding-files