java批量删除redis中以某字符串前缀的key

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/geyouchao/article/details/51136063

由于我测试的redis的环境是集群环境,故声明多个Jedis对象,下面是实现代码

package com.gyc.test;

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);
		}
	}
}


阅读更多
换一批

没有更多推荐了,返回首页