开发者

How do I keep a datastructure in sync across several servers in Java?

Have a Map which contains objects that I want to keep in sync across multiple servers, such that if objects in the map are created, deleted, or modified - this is reflected immediately (ie. within a second or two) across all servers, in a way that can potentially scale up to tens of servers.

Is there a lightweight open source Java tool that can do something like this? I'm aware of Terracotta but it is rather heavy 开发者_JAVA技巧weight for what I need.

edit: The map is backed by a DB (specifically, Apache Cassandra) - but I need my clients to be informed of any changes to it within seconds, which would mean that I would need to poll Cassandra very frequently unless there is some other means to notify clients that the map has changed.


You can use Hazelcast. If you are trying to share the same Map, Hazelcast will automatically do this for you. Here is the code for this:

java.util.Map<String, Customer> distributedMap = Hazelcast.getMap("customers");

All JVM's using "customers" map will see exactly the same data, even if it is updated frequently. If you also want to be notified whenever Map is changed then you can add listener. Here is how:

com.hazelcast.core.IMap<String, Customer> distributedMap = Hazelcast.getMap("customers");
distributedMap.addEntryListener(new EntryListener() {
        public void entryAdded(EntryEvent entryEvent) {
            System.out.println("Entry added");
        }

        public void entryRemoved(EntryEvent entryEvent) {
            System.out.println("Entry removed");
        }

        public void entryUpdated(EntryEvent entryEvent) {
            System.out.println("Entry updated");
        }

        public void entryEvicted(EntryEvent entryEvent) {
            System.out.println("Entry evicted");
        })


I think Terracotta VM clustering is the way to go. (I don't know how "multiple servers" combine with "light-weight")


I doubt you would find anything more lightweight than Terracotta. Why not use DB with second level caching?


You would have to be more specific, For example, is the map backed by a DB, or is it just within the app memory (like in the session or something)?

I've seen cache implementations that do something similar via JMS message queues etc (JCS from apache for example).

If you're in the mood, you could roll your own solutions that involves JMS topics, listeners and publishers, but this is not very trivial in practice. And I'm not sure if it will yeild the performance you're looking for.

Commercial grade cluster/cache solutions are probably you're best solution, as the other posters have suggested.


Maybe Hazelcast could help. It has some distributed collection implementations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜