Hazelcast缓存数据库数据缓存java

时间:2015-10-17 06:18:27

标签: java caching hazelcast hazelcast-imap

此类实现MapStore

package jdbc;
import com.hazelcast.core.MapStore;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import static java.lang.String.format;
import data.Person;

public class PersonMap implements MapStore<Long, Person> {

    private final Connection con;
    private PreparedStatement allKeysStatement;

    public PersonMap() throws ClassNotFoundException {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr");
           /* con.createStatement().executeUpdate(
                    "create table if not exists person (id bigint not null, name varchar(45), primary key (id))");*/
            allKeysStatement = con.prepareStatement("select * from person");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public synchronized void delete(Long key) {
        System.out.println("Delete:" + key);
        try {
            con.createStatement().executeUpdate(
                    format("delete from person where id = %s", key));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public synchronized void store(Long key, Person value) {
        try {
            con.createStatement().executeUpdate(
                    format("insert into person values(%s,'%s')", key, value.name));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public synchronized void storeAll(Map<Long, Person> map) {
        for (Map.Entry<Long, Person> entry : map.entrySet())
            store(entry.getKey(), entry.getValue());
    }

    public synchronized void deleteAll(Collection<Long> keys) {
        for (Long key : keys) delete(key);
    }

    public synchronized Person load(Long key) {
        try {
            ResultSet resultSet = con.createStatement().executeQuery(
                    format("select name from person where id =%s", key));
            try {
                if (!resultSet.next()) return null;
                String name = resultSet.getString(1);
                return new Person(key, name);
            } finally {
                resultSet.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public synchronized Map<Long, Person> loadAll(Collection<Long> keys) {
        Map<Long, Person> result = new HashMap<Long, Person>();
        for (Long key : keys) result.put(key, load(key));
        return result;
    }

    public Iterable<Long> loadAllKeys() {
        return new StatementIterable<Long>(allKeysStatement);
    }

}
这是人类 包装数据; import java.io.Serializable;

public class Person implements Serializable {

    public Long id;
    public String name;

    public Person() {
    }

    public Person(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public String toString() {
        return "Person{name='" + name + "'}";
    }
}

这个主要方法类但我无法在实例中加载数据。

import com.hazelcast.core.*;
import com.hazelcast.config.*;
import com.hazelcast.config.MapStoreConfig.InitialLoadMode;

import data.Person;

import java.util.Map;
import java.util.Queue;

import jdbc.PersonMap;

public class GettingStarted {
    public static void main(String[] args) throws ClassNotFoundException {
       /* Config cfg = new Config();
        HazelcastInstance instance = Hazelcast.newHazelcastInstance(cfg);
        Map<Integer, String> mapCustomers = instance.getMap("customers");
        mapCustomers.put(1, "Joe");
        mapCustomers.put(2, "Ali");
        mapCustomers.put(3, "Avi");
        HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(cfg);
        Map<Integer, String> mapCustomers1 = instance.getMap("customers");
        mapCustomers1.get(1);

        System.out.println("Customer with key 1: "+ mapCustomers1.get(1));
        System.out.println("Map Size:" + mapCustomers1.size());

        Queue<String> queueCustomers = instance.getQueue("customers");
        queueCustomers.offer("Tom");
        queueCustomers.offer("Mary");
        queueCustomers.offer("Jane");
        System.out.println("First customer: " + queueCustomers.poll());
        System.out.println("Second customer: "+ queueCustomers.peek());
        System.out.println("Queue size: " + queueCustomers.size());*/
        Config config = new Config();
         PersonMap simpleStore = new PersonMap();
      //  XmlConfigBuilder configBuilder = new XmlConfigBuilder();
       // Config config = configBuilder.build();
        MapConfig mapConfig = config.getMapConfig("personMap");

        MapStoreConfig mapStoreConfig = new MapStoreConfig();
        mapStoreConfig.setImplementation(simpleStore);
        mapStoreConfig.setWriteDelaySeconds(0);
        mapStoreConfig.setInitialLoadMode(InitialLoadMode.EAGER);
        mapConfig.setMapStoreConfig(mapStoreConfig);
        HazelcastInstance hz = Hazelcast.newHazelcastInstance(config);
        IMap<Long, Person> personMap = hz.getMap("personMap");
        System.out.println(personMap);
        Person p = personMap.get(1);
        System.out.println(p);

    }
}

请帮我加载数据..返回null 我尝试用两个节点运行它..但数据库数据不会来.. 数据库插入可以同步地反映在地图中

1 个答案:

答案 0 :(得分:1)

从快速浏览一下,您的HZ配置似乎没问题。

几个问题:

allKeysStatement = con.prepareStatement("select * from person");

您在这里加载整个人,而不是钥匙。 Afaik你的查询应该是这样的&#39;从人选择id&#39;

还要在PersonMap中添加一些日志记录语句(请将其重命名为PersonMapStore以防止名称混淆。您的PersonMap不是地图)。这样您就可以看到正在进行的调用。特别是对loadAllKeys和loadAll的调用对于记录是很重要的。添加日志后,您可以更新帖子,以便我们查看正在发生的事情。