首页 文章

Apache Ignite缓存未命中处理程序

提问于
浏览
0

目前我们使用guava来缓存几个db实体 . 我正在评估分发apache点燃以取代 Guava . 在 Guava 中,使用CacheLoader可以获得语义 . 如何通过点燃实现相同的功能 .

1 回答

  • 0

    通过这篇伟大的文章https://dzone.com/articles/apache-ignite-how-to-read-data-from-persistent-sto得到了答案 . 如果存在高速缓存未命中,我们可以通过高速缓存存储从db获取它,如下所示

    public class PersonStore implements CacheStore<Long, Person> {
    
    @SpringResource(resourceName = "dataSource")
    private DataSource dataSource;
    
    // This method is called whenever IgniteCache.loadCache() method is called.
    @Override
    public void loadCache(IgniteBiInClosure<Long, Person> clo, @Nullable Object... objects) throws CacheLoaderException {
        System.out.println(">> Loading cache from store...");
    
        try (Connection conn = dataSource.getConnection()) {
            try (PreparedStatement st = conn.prepareStatement("select * from PERSON")) {
                try (ResultSet rs = st.executeQuery()) {
                    while (rs.next()) {
                        Person person = new Person(rs.getLong(1), rs.getLong(2), rs.getString(3), rs.getInt(4));
    
                        clo.apply(person.getId(), person);
                    }
                }
            }
        }
        catch (SQLException e) {
            throw new CacheLoaderException("Failed to load values from cache store.", e);
        }
    }
    
    // This method is called whenever IgniteCache.get() method is called.
    @Override
    public Person load(Long key) throws CacheLoaderException {
        System.out.println(">> Loading person from store...");
    
        try (Connection conn = dataSource.getConnection()) {
            try (PreparedStatement st = conn.prepareStatement("select * from PERSON where id = ?")) {
                st.setString(1, key.toString());
    
                ResultSet rs = st.executeQuery();
    
                return rs.next() ? new Person(rs.getLong(1), rs.getLong(2), rs.getString(3), rs.getInt(4)) : null;
            }
        }
        catch (SQLException e) {
            throw new CacheLoaderException("Failed to load values from cache store.", e);
        }
    }
    
    // Other CacheStore method implementations.
    …
    

    }

相关问题