在 spring 服务类的所有实例之间共享一个 hashmap 实例 [英] sharing one instance of a hashmap between all instances of spring service class
问题描述
我打算创建一个实时计数器.因此,一个用户可以增加特定键的计数器值.而另一个通过 ajax 请求(在循环中,或使用一些长轮询方法)获取更新的计数值.我将使用一个弹簧控制器,它将注入服务类我可以做如下的事情,或者有更好的方法:
I intend to create a realtime counter. So one user can incremenet the counter value for specific key. Whilst another gets the updated count value via an ajax request (either in a loop, or using some long polling method). I will use a spring controller, which will inject the service class can I do something like below, or is there a better way :
@Service
public MyService{
//instance variable in spring injected service class, not sure if this correct
static final Map<String, Integer> myMap;
public void add(String key){
Integer count = myMap.get(key);
count++;
myMap.put(key, count);
}
//accessed via ajax loop (and controller), if value changes update display
public Integer getCount(String key){
return myMap.get(key)
}
@PostConstruct
public load(){
myMap = new HashMap<String, Integer>(10){{//initialize}};
}
编辑有几个答案,但不清楚哪个是最好的:同步添加方法?在另一个类(带注释的存储库)中创建映射并注入?还有什么?
Edit there are a few answers but it is not clear which is the best : Synchronize the add method ? Create map in another class(annotated repository) and inject that ? Something else ?
推荐答案
你可以,但需要注意那些问题:
You can, but need to be aware of those problems:
- 地图最初是空的,但您从不检查空计数器;
- add() 方法不会修改地图中的计数器.您需要在增加计数器后将其放回地图中,因为 Integer 是不可变的.或者你需要在地图中存储可变计数器
- 多个线程在没有任何同步的情况下访问地图,这将导致错误、不稳定行为或异常
- 如果您的应用聚集在多个服务器中,此策略显然会失败
这篇关于在 spring 服务类的所有实例之间共享一个 hashmap 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!