Java Spring boot:如何每小时在缓存中存储随机数?



我正试图找到一种方法来存储在缓存中的随机值。当用户收到请求时,它不会调用随机数生成,而是使用存储的值。它将每小时更新一次随机生成器。

这是正确的方法,还是有更有效的代码?

@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();
}
}

这不是spring特定的答案,而是从创建一个类变量开始,该变量将在调用之间存储值,我们可以通过将int random_value移出方法并进入类,并直接从getRandomValue()方法返回它,如return random_value;

把它们放在一起可能看起来有点像这样:

@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();
}
}

最新更新