Hazelcast地图同步 [英] Hazelcast map synchronization
问题描述
我正在尝试在应用程序中使用Hazelcast实现分布式缓存.我正在使用Hazelcast的IMap
.我遇到的问题是,每当我从地图上获取一个值并更新该值时,都需要再次执行put(key, value)
.如果我的值对象具有10个属性,并且必须更新所有10个属性,则必须调用put(key, value)
10次.像-
I am trying to implement distributed cache using Hazelcast in my application. I am using Hazelcast’s IMap
. The problem I have is every time I get a value from a map and update the value, I need to do a put(key, value)
again. If my value object has 10 properties and I have to update all 10, then I have to call put(key, value)
10 times. Something like -
IMap<Integer, Employee> mapEmployees = hz.getMap("employees");
Employee emp1 = mapEmployees.get(100);
emp1.setAge(30);
mapEmployees.put(100, emp1);
emp1.setSex("F");
mapEmployees.put(100, emp1);
emp1.setSalary(5000);
mapEmployees.put(100, emp1);
如果我不这样做,则在同一Employee对象上运行的其他某个节点将对其进行更新,最终结果是该雇员对象未同步.有什么解决方法可以避免多次调用显式调用?在ConcurrentHashMap
中,我不需要这样做,因为如果更改对象,地图也会被更新.
If I don’t do this way, some other node which operates on the same Employee object will update it and the final result is that the employee object is not synchronized. Is there any solution to avoid calling put explicitly multiple times? In a ConcurrentHashMap
, I don’t need to do this because if I change the object, the map also gets updated.
推荐答案
从3.3版开始,您将要使用EntryProcessor:
As of version 3.3 you'll want to use an EntryProcessor:
您在这里真正想做的是建立一个EntryProcessor<Integer, Employee>
并使用
mapEmployees.executeOnKey( 100, new EmployeeUpdateEntryProcessor(
new ObjectContainingUpdatedFields( 30, "F", 5000 )
);
What you really want to do here is build an EntryProcessor<Integer, Employee>
and call it using
mapEmployees.executeOnKey( 100, new EmployeeUpdateEntryProcessor(
new ObjectContainingUpdatedFields( 30, "F", 5000 )
);
通过这种方式,Hazelcast可以将地图锁定在该Employee对象的键上,并允许您原子地运行EntryProcessor的process()
方法中的任何代码,包括更新地图中的值.
This way, Hazelcast handles locking the map on the key for that Employee object and allows you to run whatever code is in the EntryProcessor's process()
method atomically including updating values in the map.
因此,您将使用一个自定义构造函数实现EntryProcessor
,该构造函数接受一个包含要更新的所有属性的对象,然后在process()
中构造最终的Employee
对象,该对象将最终出现在地图中并执行entry.setValue()
.不要忘记为EmployeeUpdateEntryProcessor
创建一个可以序列化Employee
对象的新StreamSerializer
,这样您就不会陷入java.io序列化的麻烦.
So you'd implement EntryProcessor
with a custom constructor that takes an object that contains all of the properties you want to update, then in process()
you construct the final Employee
object that will end up in the map and do an entry.setValue()
. Don't forget to create a new StreamSerializer
for the EmployeeUpdateEntryProcessor
that can serialize Employee
objects so that you don't get stuck with java.io serialization.
来源: http://docs.hazelcast.org/docs/3.5/manual/html /entryprocessor.html
这篇关于Hazelcast地图同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!