Spring Boot Asynchronous Background Queue

I am very new to Spring Boot. So please excuse my rookie mistakes. I want to run tasks asynchronously in the background while my Spring Boot application is running.

I have 3 entities:

EntityCustomer.java:

@Getter
@Table(name = "customer")
@Entity(name = "Customer")
public class EntityCustomer {

    @Id
    @GeneratedValue
    @ColumnDefault("gen_random_uuid()")
    @JdbcType(PostgreSQLUUIDJdbcType.class)
    private UUID uuid;

    @JsonManagedReference
    @OneToMany(mappedBy = "customer")
    private final List<EntityAccount> accounts = new ArrayList<>();

    public EntityCustomer() {
    }
}

EntityAccount.java:

@Getter
@Table(name = "account")
@Entity(name = "Account")
public class EntityAccount {

    @Generated
    @Id
    @ColumnDefault("gen_random_uuid()")
    private UUID uuid;

    @Setter
    @JsonBackReference
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "customer_uuid", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    private EntityCustomer customer;

    public EntityAccount() {
    }
}

EntityTransferRequest.java

@Getter
@Table(name = "transfer_request")
@Entity(name = "TransferRequest")
public class EntityTransferRequest {

    @Id
    @GeneratedValue
    @ColumnDefault("gen_random_uuid()")
    @JdbcType(PostgreSQLUUIDJdbcType.class)
    private UUID uuid;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "account_uuid", nullable = false)
    private EntityAccount account;

    @Setter
    @Column(name = "amount")
    private BigDecimal amount;

    @Setter
    @Enumerated(EnumType.STRING)
    @Column(name = "status")
    private Status status;

    public enum Status {
        PENDING,
        PROCESSING,
        COMPLETED,
        FAILED
    }
}

I need to process transfer requests one per customer at a time. So, say if there are 2 transfer requests from different accounts but accounts that are associated to the same customer; in that case one should be processed at a time. But all customers’ transfer requests should be processed asynchronously.

I tried creating a service, and mapping customers to executor services. Although I think this is a poor concept, this was what had become after researching on the internet for hours.

TransferService.java:

@Slf4j
@Service
public class TransferService {
    private final TransferRequestRepository transferRequestRepository;
    private final CustomerRepository customerRepository;
    private final ConcurrentHashMap<UUID, ExecutorService> customerExecutors;

    public TransferService(TransferRequestRepository transferRequestRepository, CustomerRepository customerRepository) {
        this.transferRequestRepository = transferRequestRepository;
        this.customerRepository = customerRepository;
        this.customerExecutors = new ConcurrentHashMap<>();
    }

    @Scheduled(fixedDelay = 5000) // runs every 5 seconds
    public void processTransfers() {
        List<EntityTransferRequest> tasks = transferRequestRepository.findFirstTaskByStatusForAllCustomers(EntityTransferRequest.Status.PENDING);
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (EntityTransferRequest task : tasks) {
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                task.setStatus(EntityTransferRequest.Status.PROCESSING);
                transferRequestRepository.save(task);
                try {
                    Thread.sleep(10000L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } // for testing
            }, customerExecutors.computeIfAbsent(task.getAccount().getCustomer().getUuid(), k -> Executors.newSingleThreadExecutor()));
            futures.add(future);
        }
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
    }
}

TransferRequestRepository.java:

public interface TransferRequestRepository extends JpaRepository<EntityTransferRequest, UUID> {

    @Query("SELECT tt FROM TransferRequest tt WHERE tt.uuid IN (SELECT MIN(tr.uuid) FROM TransferRequest tr WHERE tr.status = :status GROUP BY tr.account.customer.uuid)")
    List<EntityTransferRequest> findFirstTaskByStatusForAllCustomers(@Param("status") EntityTransferRequest.Status status);
}

But this didn’t work as I expected. I got this error when I ran my application:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'transferService' defined in file []: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'transferRequestRepository' defined in com.example.untitled.repository.TransferRequestRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract java.util.List com.example.untitled.repository.TransferRequestRepository.findFirstTaskByStatusForAllCustomers(com.example.untitled.entity.EntityTransferRequest$Status); Reason: Validation failed for query for method public abstract java.util.List com.example.untitled.repository.TransferRequestRepository.findFirstTaskByStatusForAllCustomers(com.example.untitled.entity.EntityTransferRequest$Status)

I’m pretty sure there must be a much better way to implement this logic. I appreciate you taking time to help me solve this issue.

New contributor

user25627638 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật