如何在集群环境中使用redis扫描?

问题描述 投票:-1回答:2

我正在使用spring redisTemplate和redis scan

它可以在单个节点的条件下找到。

但在集群环境中它不起作用

我无法获得数据。

有没有办法在集群环境中获取扫描数据?

这是我的spring redisTemplate代码。

        //String key="products:aa";
        //String key="products:aac";
        //String key="products:ab";
        //String key="products:ac";


        String workKey="products:aa*";
        ScanOptions options = ScanOptions.scanOptions().match(workKey).count(100).build();

        ScanOptions options1 = ScanOptions.scanOptions().build();
        RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
        RedisConnection conn = factory.getConnection();
        Cursor<byte[]> cursor = conn.scan(options);
        List<Product> result = new ArrayList<Product>();
        while(cursor.hasNext()){
            String key=new String((byte[]) cursor.next());
            Product pa=getById(key.replace("products:",""));
            result.add(pa);
        }

        //result 
        //String key="products:aa";
        //String key="products:aac";
redis spring-data spring-data-redis redis-cluster
2个回答
2
投票

扫描是单个redis节点的命令。如果确实要在群集中使用它,请先在群集中获取节点列表,然后对每个节点运行扫描。


1
投票

是同意,扫描用于单个节点。您必须扫描群集的每个节点[主]。下面是使用predis删除群集模式中匹配字符串的所有键的示例。

/ *删除具有匹配文本的多个密钥* /

public function removeMatchedKeys($keyName){
    $allRedisHost = array(host1,host2)
    if(!empty($allRedisHost ) && is_array($allRedisHost )) {
        foreach($allRedisHost as $key=>$host) {
            $singleRedisNode =  new Predis\Client("tcp://$host:6379");
            $it = NULL;
            $arr_keys_arr = array();
            $searchKeyName= $prefix.":".$keyName.":*";
            $i=0;
            foreach (new Iterator\Keyspace($singleRedisNode, $searchKeyName) as $actualKey) {
                $actualKey = str_replace($prefix . ':', '', $actualKey);
                $this->predis->del($actualKey);
                $i++;
            }
        }
    }
}

这里“Iterator \ Keyspace”内部使用扫描方法。只需要包含Iterator类[Predis \ Collection \ Iterator]。

© www.soinside.com 2019 - 2024. All rights reserved.