使用Predicate搜索Hazelcast中的键集

时间:2015-02-18 18:41:20

标签: hazelcast

我是Hazelcast的新手 - 评估和原型设计,看它是否符合我们的分布式内存缓存需求。 其中一个要求是能够使用通配符搜索给定地图中的键。查看IMap文档,看起来可以使用keySet(谓词谓词)。但我无法想象如何使用谓词,以便给定一个通配符字符串,返回包含所有匹配键的keySet。一个例子会有所帮助。

我的代码片段。这是客户端。

IMap<String, String> mapTest1 = client.getMap("testMap");

mapTest1.put( "testKey1", "This is a Test" );
mapTest1.put( "testKey2", "This value has a long key name" );
mapTest1.put( "key3", "Another value" );
// Need a wild card search on the map, such that all keys with "%test%" will be returned.

感谢。

1 个答案:

答案 0 :(得分:2)

如果我理解你的请求,这应该可以解决问题:

public class Test {

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

        IMap<String, String> map = hazelcastInstance.getMap("someMap");
        Collection<String> keys = map.keySet(
            new RegexPredicate("[a-z].*[a-z0-9]"));

        System.out.println(keys);
     }

     public static class RegexPredicate implements Predicate<String, String> {

        private String regex;
        private transient Pattern pattern;

        public RegexPredicate(String regex) {
            this.regex = regex;
        }

        @Override
        public boolean apply(Map.Entry<String, String> mapEntry) {
            if (pattern == null) {
                 pattern = Pattern.compile(regex);
            }
            Matcher matcher = pattern.matcher(mapEntry.getKey());
            return matcher.matches();
        }
    }
}
相关问题