批量删除redis中以某字符串前缀的key
2018-03-24 18:27:06
2244次阅读
0个评论
因为测试redis的环境是集群环境,所以声明多个Jedis对象,下面是实现代码
import java.util.Iterator;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;
public class TestRedis {
private Jedis jedis;
private Jedis jedis1;
private Jedis jedis2;
private Jedis jedis3;
private String pre_str = "a"; //redis的key的前缀
@Before
public void setup() {
System.out.println("---------------------------------setup------------------");
// 连接redis服务器,127.0.0.1:6379
// jedis = new Jedis("127.0.0.1", 6379);
jedis1 = new Jedis("127.0.0.1", 6377);
jedis2 = new Jedis("127.0.0.2", 6378);
jedis3 = new Jedis("127.0.0.3", 6379);
// 权限认证
// jedis.auth("admin");
}
/**
* redis批量删除以某字符串前缀的key
*/
@Test
public void testBatchDel() {
System.out.println("---------------------------------testBatchDel------------------");
batchDel(jedis1);
batchDel(jedis2);
batchDel(jedis3);
}
private void batchDel(Jedis jedis){
Set<String> set = jedis.keys(pre_str +"*");
Iterator<String> it = set.iterator();
while(it.hasNext()){
String keyStr = it.next();
System.out.println(keyStr);
jedis.del(keyStr);
}
}
}
00