官术网_书友最值得收藏!

Mapping back to the real world

Having briefly explored Hazelcast's distributed capabilities via a test console, let's have a look at how we are more likely to interact with a cluster in the real world. Let's create a new SimpleMapExample class with a main method to spin up and manipulate a named distributed map called capitals. Hazelcast refers to these named collections as a namespace. These collections must be uniquely named across the cluster, as follows:

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import java.util.Map;

public class SimpleMapExample {
  public static void main(String[] args) {
    HazelcastInstance hz = Hazelcast.newHazelcastInstance();

    Map<String, String> capitals = hz.getMap("capitals");
    capitals.put("GB", "London");
    capitals.put("FR", "Paris");
    capitals.put("US", "Washington DC");
    capitals.put("AU", "Canberra");

    System.err.println(
      "Known capital cities: " + capitals.size());

    System.err.println(
      "Capital city of GB: " + capitals.get("GB"));
  }
}

As was the case before, we will see various logging entries on the startup as well as the fun fact output, confirming that we persisted into and retrieved from the map programmatically. We can also use this example in conjunction with the ConsoleApp console from the previous section and interact with the new map capitals. To do this, we will need to switch namespaces from within the console before interacting with the map, as shown in the following command. Make sure that they have formed a cluster when using the console if you closed it after implementing the previous example:

hazelcast[default] > ns capitals
namespace: capitals

hazelcast[capitals] > m.get GB
London

As with the other implementations of Java maps, if you wish to create your own objects for use within a Hazelcast map, you will need to consider the use of the custom equals() and hashCode() methods. However, it is the serialized binary form of the object that is used instead of these custom methods when the object is used as a key to a Hazelcast map entry.

Note

It is generally not a good idea to use a collection or overly complex object as the key to the map entries. As they are also transferred between the nodes via Hazelcast, multiple serialization transformations may taint the eventual serialized binary form that is used in the map lookup and might result in returning incorrect or null data.

主站蜘蛛池模板: 莱州市| 西乌珠穆沁旗| 宣武区| 上饶市| 鹤岗市| 广东省| 凤翔县| 凤冈县| 隆安县| 泾川县| 互助| 信宜市| 台东市| 文山县| 安仁县| 亳州市| 凌海市| 双流县| 闻喜县| 稻城县| 石台县| 南丹县| 石景山区| 武宁县| 鄂伦春自治旗| 蒙自县| 郴州市| 水城县| 德惠市| 颍上县| 武汉市| 斗六市| 山西省| 灵宝市| 通渭县| 内丘县| 丰顺县| 水城县| 泰来县| 仁怀市| 柳河县|