0

I have a method that updates the database with User's referencenumber and then i have a Spring retry mechanism to retry and check if the User's record is updated with reference number. But the retry call doesnt fetch the latest record from Database. I dont have problem with updating the record, but only with fetch, its not fetching the latest updated record.

UserRetryTemplate



@Component
public class UserRetryTemplate {


    @Value("${retry.max.attempts:5}")
    private int maxAttempts;

    @Value("${response.waiting.time.in.seconds:60}")
    private long maxDelay;

    @Autowired
    private UserRepository userRepository;

    private static final long INITIAL_INTERVAL = 2000L;

    public RetryTemplate retryTemplate() {

        // Max timeout in milliseconds
        long maxTimeout = maxDelay*1000;

        //double multiplier = (maxTimeout - INITIAL_INTERVAL)/((maxAttempts-2)*6000);

        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(maxAttempts);


        FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
        backOffPolicy.setBackOffPeriod(maxTimeout/(maxAttempts-1));

        RetryTemplate template = new RetryTemplate();
        template.setRetryPolicy(retryPolicy);
        template.setBackOffPolicy(backOffPolicy);
        return template;
    }

    public boolean doUserReferenceRetry(String userId) {
        boolean isUserReferenceValid = true;
        try {
            boolean isValidUser = retryTemplate().execute(context -> {
                logger.info("Attempted {} times", context.getRetryCount());
                User user = userRepository.findByUserName(userId);
                logger.info("User Retry :" + user);

                if (user.getResponseDateItem() == null || user.getReferenceNumber == null) {
                    logger.info("response not yet received");
                    throw new IllegalStateException("User Response not yet received");
                }
                if (user.getReferenceNumber != null)) {
                    return true;
                }
                throw new IllegalStateException("Response not yet received");
            });
            return isUserReferenceValid ;
        } catch (IllegalArgumentException e) {

        }
        return true;
    }

}

UserRepository.java

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    User findByUserName(String userName);

}

UserManagerImpl

public void updateReference(String userId, String referenceNumber) {

        User user = userRepository.findById(userId);
        if (user != null) {
            user.setReference(referenceNumber);
            user.setResponseDate(DateHelper.createXMLGregorianCalendar());
            userRepository.saveAndFlush(user);
        }
    }

The Queue when processing the response, updates the referenceNumber for the User in DB (which is working fine)

UserQueueClient :

@Component
public class UserQueueClient {



    @JmsListener(id = "#{T(java.util.UUID).nameUUIDFromBytes('${in.res}",
            destination = "${in.res}", containerFactory = "containerFactory")
    public void receive(Message message, UserEnvelopeV1_0 envelope) throws{


        try {
            String userId = envelope.getHeader().getMessageIdentification().getUserId();
 ApplicationInformationStructure applicationInformation = envelope.getBody().getApplicationInformation();

if(CollectionUtils.isNotEmpty(applicationInformation.getApplicationInformationResult())) {
          String referenceNumber = applicationInformation.getApplicationInformationResult().getRefNumber();      

                userManager.updateReference(userId, referenceNumber);
            }

        } catch (Exception e) {
            //
        }
    }


}

So there is other process which updates the reference number, which is working fine and it updates the DB with the value. But the read ( from the Retry Template) doesnt fetch the updated record.

Dev
  • 31
  • 1
  • 8
  • You need to save the object. – Patrick Santana Apr 03 '20 at 07:16
  • I do save the object in different method which i didn't mention. This code i added is only the fetch part. – Dev Apr 03 '20 at 07:19
  • @Jens Schauder, This is not associated with the question that you mentioned. You must please read the question properly before closing it. The question that you sent is related to update not happening properly. My question is not about update not happening. Its about the fetch thats not happening as i want it. So, its 2 different issues. Can you please reopen it – Dev Apr 03 '20 at 08:19
  • It is the same problem. The update is working just fine as in your case. It is just that an `EntityManager` does not refetch entities already in the first level cache. You need to evict the entities first or use `refresh` or a fresh `EntityManager`. Please do not assume I didn't read the questions before closing them. – Jens Schauder Apr 03 '20 at 09:17
  • I added another answer to the referenced question which might the situation easier to understand. – Jens Schauder Apr 03 '20 at 09:42

0 Answers0