我要创建应用程序范围文档计数器。添加新文档的每个用户将获得唯一的递增数字。问题是它如何在groovy中制作。我需要变量,它只是一个实例用于整个应用程序,并且是多访问的。其他建议也很受欢迎。
答案 0 :(得分:0)
基于以下假设:
`
import java.util.concurrent.atomic.AtomicInteger;
/**
* This class contains application context
*/
public class AppContext {
private static int INIT_VAL = 1;
static {
//TODO:may need to have the INIT_VAL restored from file/db if required
}
private static final AtomicInteger counter = new AtomicInteger(INIT_VAL);
/**
* Gets the current state of counter
* @return current counter val
*/
public static int getCounter(){
return counter.get();
}
/**
* Increments counter by one
* @return increments and gets the counter value
*/
public static int incrementCounter(){
//TODO: may store/update the value to a file/db if counter needs to be preserved after restart
return counter.incrementAndGet();
}
}
`