javaspring-bootspring-cachespring-scheduled

Java Spring boot: How do I Store random number in cache every hour?


I am trying to find a way to store a random value in the cache. When user get requests, it will Not call random number generate, but use the value stored. It will update the random generator every hour .

Is this the correct way to do this, or is there more efficient code?

@Service
class TestService {
 
  private int createRandomValue() {
      Random rand = new Random(); 
      int random_value = rand.nextInt(100); 
      return random_value;
  }

  @Cacheable(value = "randomvalue")
  public int getRandomValue() {
      return createRandomValue();
  }
   
 @CachePut(value = "randomvalue")
 @Scheduled(fixedDelay = 36000)
 public int updateRandomValue() {
      return createRandomValue();
 }
}

Solution

  • This isn't a spring specific answer, but start by creating a class variable that will store the value between calls, which we can do by moving int random_value out of the method and into the class, and returning it directly from the getRandomValue() method like so return random_value;.

    All together it might look a bit like this:

    @Service
    class TestService {
      //Class variable
      private int random_value = 0;
    
      private int createRandomValue() {
          Random rand = new Random(); 
          //Update the class variable
          random_value = rand.nextInt(100); 
          return random_value;
      }
    
      @Cacheable(value = "randomvalue")
      public int getRandomValue() {
          //Return the stored class variable
          return random_value;
      }
       
      @CachePut(value = "randomvalue")
      @Scheduled(fixedDelay = 36000)
      public int updateRandomValue() {
          return createRandomValue();
      }
    }