RedisTemplate 使用scan扫描数据

原创
08/13 08:03
阅读数 1K

根据指定key前缀找到对应的key集合 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;

@RestController
public class HomeController {


    @Autowired
    private RedisConnectionFactory connectionFactory;


    String prefix = "ad\\.jpush\\.prfix\\.";

    @GetMapping("/")
    public String index() {
        RedisConnection connection = null;
        try {
            connection = connectionFactory.getConnection();
            ScanOptions scanOptions = ScanOptions.scanOptions().count(10L).match(prefix + "*").build();
            Cursor<byte[]> cursors = connection.scan(scanOptions);

            cursors.forEachRemaining(new Consumer<byte[]>() {
                @Override
                public void accept(byte[] bytes) {
                    String key = new String(bytes, StandardCharsets.UTF_8);
                    System.out.println(key);

                }
            });
        } finally {
            RedisConnectionUtils.releaseConnection(connection, connectionFactory);
        }

        return "index";
    }


}

RedisConnection 封装了对redis 的操作,大家可以点进去看看

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部