[英]Spring Boot and Amazon AWS - how to connect to S3 using Spring Cloud AWS?
[英]How to do transaction using aws s3 in Spring Boot
我使用 java 的 spring 引导编写了图像上传方法,如下所示。
它在上传名为 Todo class 的图像之前保存标题和图像路径等。
@Override
public Todo saveTodo(String title, String description, MultipartFile file) {
// check if the file is empty
if (file.isEmpty()) {
throw new IllegalStateException("Cannot upload empty file");
}
// Check if the file is an image
if (!Arrays.asList(IMAGE_PNG.getMimeType(), IMAGE_BMP.getMimeType(), IMAGE_GIF.getMimeType(),
IMAGE_JPEG.getMimeType()).contains(file.getContentType())) {
throw new IllegalStateException("FIle uploaded is not an image");
}
// get file metadata
Map<String, String> metadata = new HashMap<>();
metadata.put("Content-Type", file.getContentType());
metadata.put("Content-Length", String.valueOf(file.getSize()));
// Save Image in S3 and then save Todo in the database
String path = String.format("%s/%s", amazonConfig.getBucketName(), UUID.randomUUID());
String fileName = String.format("%s", file.getOriginalFilename());
Todo todo = Todo.builder().description(description).title(title).imagePath(path).imageFileName(fileName)
.build();
repository.save(todo);
try {
fileStore.upload(path, fileName, Optional.of(metadata), file.getInputStream());
} catch (IOException e) {
throw new IllegalStateException("Failed to upload file", e);
}
return repository.findByTitle(todo.getTitle());
}
但是当上传发生错误时,我想完全删除插入的待办事项。
我可以在 catch 中使用存储库删除方法手动删除。
但是我可以在没有删除方法的情况下只写@transacion 或其他东西来执行此操作吗?
感谢您阅读我的问题。
只需使用@Transactional
注释saveTodo
方法。
它看起来像这样:
import org.springframework.transaction.annotation.Transactional;
// other imports
// other code
@Override
@Transactional
public Todo saveTodo(....
如果发生 RuntimeException,它将回滚。 (IllegalStateException 是一个 RuntimeException,所以它会正常工作)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.