【发布时间】:2015-04-01 14:45:56
【问题描述】:
我有一个客户端应用程序每 1 秒从一个 url 请求一些信息。
在服务器(一个servlet & JSP 应用程序)中,为了避免不必要的DB 访问,实现了下一个解决方案。这是一个sn-p:
//a static HashMap where we save the last record inserted in db
public static Map<Long, Long> VALUES = new HashMap<Long, Long>();
// A lastRecordRead sent by the client
if (VALUES.get(id) != lastRecordRead) {
//Access the database to get some information
//cause the last value read is different from the last record inserted
...
}else{
//Do nothing
//It's not necessary access DB cause the parameters match
}
这在开发环境中按预期工作。
当我们有一个集群环境时,问题就来了。我们将服务器部署在两个节点中(使用 jboss),每个节点都有自己的 HashMap 和自己的值。所以根据我们攻击的节点,我们可以 获取不同的值...
¿有没有办法在两个节点之间共享这个 HashMap?我正在寻找一些不需要更新 2 个地图的答案,这意味着不需要在节点之间调用...
我们将不胜感激。
编辑:我现在正在玩 HazelCast,它看起来很容易,我担心我做错了什么......
在我的服务器中,我现在使用 HazelCast 而不是 HasMap:
public static Map<Long, Long> VALUES = (Hazelcast.newHazelcastInstance(new Config())).getMap("VALUES");
插入记录时:
if (((VALUES.get(id) == null)||(VALUES.get(id) < lastIdInserted))) {
VALUES.put(id, lastIdInserted);
}
当客户端应用调用服务器时:
// A lastRecordRead sent by the client
if (VALUES.get(id) != lastRecordRead) {
//Access the database to get some information
//cause the last value read is different from the last record inserted
...
}else{
//Do nothing
//It's not necessary access DB cause the parameters match
}
我认为,仅此而已。任何人都可以确认这是否可以或我错过了什么..?这个解决方案是否真的遍布所有节点?我一直在用 2 个 tomcat 进行测试,它确实有效,但它可以与不同的 ips 一起工作吗?
【问题讨论】:
标签: java production-environment