Java Code Examples for redis.clients.jedis.Jedis#keys()

The following examples show how to use redis.clients.jedis.Jedis#keys() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClientTest.java    From JRediSearch with BSD 2-Clause "Simplified" License 8 votes vote down vote up
@Test
public void testDrop() throws Exception {
    Client cl = getClient();
    cl._conn().flushDB();

    Schema sc = new Schema().addTextField("title", 1.0);

    assertTrue(cl.createIndex(sc, Client.IndexOptions.defaultOptions()));
    Map<String, Object> fields = new HashMap<>();
    fields.put("title", "hello world");
    for (int i = 0; i < 100; i++) {
        assertTrue(cl.addDocument(String.format("doc%d", i), fields));
    }

    SearchResult res = cl.search(new Query("hello world"));
    assertEquals(100, res.totalResults);

    assertTrue(cl.dropIndex());

    Jedis conn = cl._conn();

    Set<String> keys = conn.keys("*");
    assertTrue(keys.isEmpty());
}
 
Example 2
Source File: JedisUtil.java    From scaffold-cloud with MIT License 7 votes vote down vote up
/**
 * 批量获取缓存
 *
 * @param pattern
 * @return 值
 */
public static List<Object> batchGetObject(String pattern) {
    Jedis jedis = null;
    List<Object> list = new ArrayList<>();
    try {
        jedis = getResource();
        Set<String> sets = jedis.keys(pattern + "*");
        if (!CollectionUtils.isEmpty(sets)) {
            for (String key : sets) {
                Object result = toObject(jedis.get(getBytesKey(key)));
                list.add(result);
            }
        }
    } catch (Exception e) {
        logger.warn("get {} = {}", pattern, list, e);
    } finally {
        close(jedis);
    }
    return list;
}
 
Example 3
Source File: BaseCache.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * 删除数据
 * @param pattern
 */
public static void removeData(String pattern){
    Jedis redis = null;
    try {
        redis = getJedis();
        Set<String> keys = redis.keys("*"+pattern);
        if(keys == null || keys.size() == 0){
            return ;
        }
        for(String key : keys){
            redis.del(key);
        }
    }finally {
        if(redis != null){
            redis.close();
        }
    }
}
 
Example 4
Source File: JedisUtil.java    From BigData with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 查找所有匹配给定的模式的键
 * 
 * @param String
 *            key的表达式,*表示多个,?表示一个
 * */
public Set<String> keys(String pattern) {
	Jedis jedis = getJedis();
	Set<String> set = jedis.keys(pattern);
	returnJedis(jedis);
	return set;
}
 
Example 5
Source File: PoolManagementTest.java    From MythRedisClient with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetRedisPool() throws Exception {
    RedisPools result = poolManagement.getRedisPool();

    System.out.println(result.getDatabaseNum());
    Jedis jedis = result.getJedis();
    jedis.keys("");
    jedis.set("names","testGetRedisPool");
    Assert.assertEquals("testGetRedisPool",jedis.get("names"));
}
 
Example 6
Source File: RedisTest.java    From java-study with Apache License 2.0 5 votes vote down vote up
/**
 * @param args
 */
public static void main(String[] args) {
	// 连接到本地的 redis服务
	Jedis jedis = new Jedis("127.0.0.1");
	System.out.println("连接成功");
	// 查看服务是否运行
	System.out.println("服务正在运行: " + jedis.ping());

	// 存储到列表中
	jedis.lpush("list", "redis");
	jedis.lpush("list", "java");
	jedis.lpush("list", "mysql");
	// 获取存储的数据并输出
	List<String> list = jedis.lrange("list", 0, 2);
	for (int i = 0, j = list.size(); i < j; i++) {
		System.out.println("list的输出结果:" + list.get(i));
	}

	// 设置 redis 字符串数据
	jedis.set("rst", "redisStringTest");
	// 获取存储的数据并输出
	System.out.println("redis 存储的字符串为: " + jedis.get("rst"));

	// 存储数据
	jedis.sadd("setTest1", "abc");
	jedis.sadd("setTest1", "abcd");
	jedis.sadd("setTest1", "abcde");
	// 获取数据并输出
	Set<String> keys = jedis.keys("*");
	// Set<String> keys=jedis.smembers("setTest1");
	// 定义迭代器输出
	Iterator<String> it = keys.iterator();
	while (it.hasNext()) {
		String key = it.next();
		System.out.println(key);
	}

}
 
Example 7
Source File: RedisRegistry.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private void clean(Jedis jedis) {
    Set<String> keys = jedis.keys(root + Constants.ANY_VALUE);
    if (keys != null && keys.size() > 0) {
        for (String key : keys) {
            Map<String, String> values = jedis.hgetAll(key);
            if (values != null && values.size() > 0) {
                boolean delete = false;
                long now = System.currentTimeMillis();
                for (Map.Entry<String, String> entry : values.entrySet()) {
                    URL url = URL.valueOf(entry.getKey());
                    if (url.getParameter(Constants.DYNAMIC_KEY, true)) {
                        long expire = Long.parseLong(entry.getValue());
                        if (expire < now) {
                            jedis.hdel(key, entry.getKey());
                            delete = true;
                            if (logger.isWarnEnabled()) {
                                logger.warn("Delete expired key: " + key + " -> value: " + entry.getKey() + ", expire: " + new Date(expire) + ", now: " + new Date(now));
                            }
                        }
                    }
                }
                if (delete) {
                    jedis.publish(key, Constants.UNREGISTER);
                }
            }
        }
    }
}
 
Example 8
Source File: RedisServiceImpl.java    From ace-cache with Apache License 2.0 5 votes vote down vote up
@Override
public Set<String> keys(String pattern) {
    Jedis jedis = null;
    Set<String> res = null;
    try {
        jedis = pool.getResource();
        res = jedis.keys(pattern);
    } catch (Exception e) {

        LOGGER.error(e.getMessage());
    } finally {
        returnResource(pool, jedis);
    }
    return res;
}
 
Example 9
Source File: RedisSessionIT.java    From personal_book_library_web_project with MIT License 5 votes vote down vote up
@Test
public void testRedisConnection() {
	
	jedis = new Jedis(environment.getProperty("redis.host"), Integer.parseInt(environment.getProperty("redis.port")));
	
	Set<String> redisResult = jedis.keys("*");
	System.out.println(redisResult);
       Assert.assertTrue(redisResult.size() > 0);
}
 
Example 10
Source File: ShardedJedisTest.java    From spring-redis-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void shardedPiplineTest() {
    StopWatch stopWatch = new StopWatch("jedis pipeline benchmark");

    stopWatch.start("jedis proxy pipeline");
    demo.incr(key, times);
    stopWatch.stop();

    stopWatch.start("shardedJedis proxy pipeline");
    shardedJedisDemo.incr(key, times);
    stopWatch.stop();

    LOGGER.info(stopWatch.prettyPrint());

    Jedis jedis1 = jedisPool.getResource();
    Set<String> set1 = jedis1.keys("test:shardedJedis*");
    LOGGER.info(String.valueOf(set1.size()));
    jedis1.del(set1.toArray(new String[set1.size()]));

    Jedis jedis2 = jedisPool6380.getResource();
    Set<String> set2 = jedis2.keys("test:shardedJedis*");
    LOGGER.info(String.valueOf(set2.size()));
    jedis2.del(set2.toArray(new String[set2.size()]));

    jedis1.close();
    jedis2.close();
}
 
Example 11
Source File: Main.java    From JavaBase with MIT License 5 votes vote down vote up
/**
 * get keys
 */
private Set<String> getKeys(RedisPools pool, RedisPoolProperty property, int database) {
  Optional<Jedis> jedisOpt = pool.getJedis(property);
  if (!jedisOpt.isPresent()) {
    return new HashSet<>(0);
  }

  Jedis jedis = jedisOpt.get();
  jedis.select(database);
  return jedis.keys("*");
}
 
Example 12
Source File: JedisCache.java    From charging_pile_cloud with MIT License 5 votes vote down vote up
public static Set<String> getAll(int dbIndex, String pattern) {
    Set<String> result = null;
    Jedis jedis = null;
    try {
        jedis = jedisManager.getJedis();
        jedis.select(dbIndex);
        result = jedis.keys(pattern);
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    } finally {
        jedis.close();
    }
    return result;
}
 
Example 13
Source File: RedisRegistry.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private void clean(Jedis jedis) {
    Set<String> keys = jedis.keys(root + Constants.ANY_VALUE);
    if (keys != null && keys.size() > 0) {
        for (String key : keys) {
            Map<String, String> values = jedis.hgetAll(key);
            if (values != null && values.size() > 0) {
                boolean delete = false;
                long now = System.currentTimeMillis();
                for (Map.Entry<String, String> entry : values.entrySet()) {
                    URL url = URL.valueOf(entry.getKey());
                    if (url.getParameter(Constants.DYNAMIC_KEY, true)) {
                        long expire = Long.parseLong(entry.getValue());
                        if (expire < now) {
                            jedis.hdel(key, entry.getKey());
                            delete = true;
                            if (logger.isWarnEnabled()) {
                                logger.warn("Delete expired key: " + key + " -> value: " + entry.getKey() + ", expire: " + new Date(expire) + ", now: " + new Date(now));
                            }
                        }
                    }
                }
                if (delete) {
                    jedis.publish(key, Constants.UNREGISTER);
                }
            }
        }
    }
}
 
Example 14
Source File: ClusterSync.java    From moon-api-gateway with MIT License 5 votes vote down vote up
private void serviceInfoSync(Jedis jedisClient) {

        Set<String> targetKeys = jedisClient.keys(String.join("-", Constant.REDIS_KEY_SERVICE_UPDATE, HttpHelper.getHostName() + serverPort + "*"));
        targetKeys.forEach(redisKey -> {
            String serviceSyncInString = jedisClient.get(redisKey);
            ServiceSync serviceSync = JsonUtil.fromJson(serviceSyncInString, ServiceSync.class);
            log.info("Found New Update Service Information - method: {}, serviceId: {}", serviceSync.getType().getDescription(), serviceSync.getServiceInfo().getServiceId());
            boolean result = syncService.syncServiceInfoToCache(serviceSync);
            if (result) jedisClient.del(redisKey);
        });

    }
 
Example 15
Source File: RedisRegistry.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
private void clean(Jedis jedis) {
    // /LTS/{集群名字}/NODES/
    Set<String> nodeTypePaths = jedis.keys(NodeRegistryUtils.getRootPath(appContext.getConfig().getClusterName()) + "/*");
    if (CollectionUtils.isNotEmpty(nodeTypePaths)) {
        for (String nodeTypePath : nodeTypePaths) {
            // /LTS/{集群名字}/NODES/JOB_TRACKER
            Set<String> nodePaths = jedis.keys(nodeTypePath);
            if (CollectionUtils.isNotEmpty(nodePaths)) {
                for (String nodePath : nodePaths) {
                    Map<String, String> nodes = jedis.hgetAll(nodePath);
                    if (CollectionUtils.isNotEmpty(nodes)) {
                        boolean delete = false;
                        long now = SystemClock.now();
                        for (Map.Entry<String, String> entry : nodes.entrySet()) {
                            String key = entry.getKey();
                            long expire = Long.parseLong(entry.getValue());
                            if (expire < now) {
                                jedis.hdel(nodePath, key);
                                delete = true;
                                if (LOGGER.isWarnEnabled()) {
                                    LOGGER.warn("Delete expired key: " + nodePath + " -> value: " + entry.getKey() + ", expire: " + new Date(expire) + ", now: " + new Date(now));
                                }
                            }
                        }
                        if (delete) {
                            jedis.publish(nodePath, Constants.UNREGISTER);
                        }
                    }
                }
            }
        }
    }
}
 
Example 16
Source File: ClusterSync.java    From moon-api-gateway with MIT License 5 votes vote down vote up
/**
 * Check whether there is new application whiltelist information issued to the node.
 * Apply that information to the node's cache and remove it from redis.
 */
private void appWhitelistSync(Jedis jedisClient) {

    Set<String> targetKeys = jedisClient.keys(String.join("-", Constant.REDIS_KEY_APP_WHITELIST_UPDATE, HttpHelper.getHostName() + serverPort + "*"));
    targetKeys.forEach(redisKey -> {
        String whitelistSyncInString = jedisClient.get(redisKey);
        WhitelistIpSync whitelistIpSync = JsonUtil.fromJson(whitelistSyncInString, WhitelistIpSync.class);
        log.info("Found New Update APP Whitelist Information - method: {}, appId: {}", whitelistIpSync.getType().getDescription(), whitelistIpSync.getAppId());
        boolean result = syncService.syncAppWhitelistToCache(whitelistIpSync);
        if (result) jedisClient.del(redisKey);
    });

}
 
Example 17
Source File: RedisRegistry.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
private void clean(Jedis jedis) {
    Set<String> keys = jedis.keys(root + Constants.ANY_VALUE);
    if (keys != null && keys.size() > 0) {
        for (String key : keys) {
            Map<String, String> values = jedis.hgetAll(key);
            if (values != null && values.size() > 0) {
                boolean delete = false;
                long now = System.currentTimeMillis();
                for (Map.Entry<String, String> entry : values.entrySet()) {
                    URL url = URL.valueOf(entry.getKey());
                    if (url.getParameter(Constants.DYNAMIC_KEY, true)) {
                        long expire = Long.parseLong(entry.getValue());
                        if (expire < now) {
                            jedis.hdel(key, entry.getKey());
                            delete = true;
                            if (logger.isWarnEnabled()) {
                                logger.warn("Delete expired key: " + key + " -> value: " + entry.getKey() + ", expire: " + new Date(expire) + ", now: " + new Date(now));
                            }
                        }
                    }
                }
                if (delete) {
                    jedis.publish(key, Constants.UNREGISTER);
                }
            }
        }
    }
}
 
Example 18
Source File: SomeOperate.java    From Redis_Learning with Apache License 2.0 4 votes vote down vote up
public static void KeyOperate(Jedis jedis, ShardedJedis shardedJedis) {

		System.out.println("==================key======================");

		// flushDB():ɾ����ǰѡ�����ݿ��е�����key
		// flushall()��ɾ���������ݿ��е�����key
		System.out.println("��տ����������ݣ�" + jedis.flushDB());

		// exists(key):�ж�key�����
		System.out.println("�ж�key999���Ƿ���ڣ�" + shardedJedis.exists("key999"));
		System.out.println("������ֵ�ԣ�" + shardedJedis.set("key001", "value001"));
		System.out.println("�ж�key001�Ƿ���ڣ�" + shardedJedis.exists("key001"));
		System.out.println("������ֵ�ԣ�" + shardedJedis.set("key002", "value002"));

		System.out.println("ϵͳ�����м����£�");
		// keys(pattern)�������������pattern������key
		Set<String> keys = jedis.keys("*");
		Iterator<String> it = keys.iterator();
		while (it.hasNext()) {
			String key = it.next();
			System.out.println(key);
		}

		// del(key):ɾ��ij��key,��key�����ڣ�����Ը����
		// Problem1��Ϊʲôɾ����Jedis�ģ���shardedJedis��Ҳɾ���ˣ�����������������������������
		System.out.println("ϵͳ��ɾ��key002: " + jedis.del("key002"));
		System.out.println("�ж�key002�Ƿ���ڣ�" + shardedJedis.exists("key002"));

		// expire(key,time)���趨һ��key�Ļʱ�䣨s��
		System.out.println("���� key001�Ĺ���ʱ��Ϊ5��:" + jedis.expire("key001", 5));

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
		}

		// ttl(key):�鿴ij��key��ʣ������ʱ��,��λ���롿����������߲����ڵĶ�����-1
		System.out.println("�鿴key001��ʣ������ʱ�䣺" + jedis.ttl("key001"));
		// �Ƴ�ij��key������ʱ��
		System.out.println("�Ƴ�key001������ʱ�䣺" + jedis.persist("key001"));
		System.out.println("�鿴key001��ʣ������ʱ�䣺" + jedis.ttl("key001"));

		// Problem2�����һ���������ˣ��������ڣ���������������
		System.out.println("����������" + jedis.get("key001"));
		// rename(oldname, newname)��������key
		System.out.println("��������" + jedis.rename("key001", "newkey001"));

		// type(key)�鿴key�������ֵ������
		System.out.println("�鿴key�������ֵ�����ͣ�" + jedis.type("newkey001"));
	}
 
Example 19
Source File: DefaultRedis.java    From craft-atom with MIT License 4 votes vote down vote up
private Set<String> keys0(Jedis j, String pattern) {
	return j.keys(pattern);
}
 
Example 20
Source File: AbstractRedisTest.java    From x-pipe with Apache License 2.0 4 votes vote down vote up
protected void assertRedisEquals(RedisMeta redisMaster, List<RedisMeta> slaves) {

        Map<String, String> values = new HashMap<>();
        Jedis jedis = createJedis(redisMaster);
        Set<String> keys = jedis.keys("*");
        for (String key : keys) {
            values.put(key, jedis.get(key));
        }

        for (RedisMeta redisSlave : slaves) {

            logger.info(remarkableMessage("[assertRedisEquals]redisSlave:" + redisSlave));

            Jedis slave = createJedis(redisSlave);
            Set<String> slaveKeys = slave.keys("*");

            Pair<Set<String>, Set<String>> diff = diff(values.keySet(), slaveKeys);
            boolean fail = false;

            if (diff.getKey().size() != 0) {
                logger.info("[lack keys]{}", diff.getKey());
                printKeysAround(diff.getKey(), slave);
                fail = true;
            }
            if (diff.getValue().size() != 0) {
                logger.info("[more keys]{}", diff.getKey());
                fail = true;
            }

            Assert.assertFalse(fail);

            Set<String> keysWrong = new HashSet<>();
            for (Entry<String, String> entry : values.entrySet()) {
                String realValue = slave.get(entry.getKey());
                if (!realValue.equals(entry.getValue())) {
                    keysWrong.add(entry.getKey());
                }
            }

            if (keysWrong.size() != 0) {
                logger.info("[keysWrong]{}", keysWrong);
            }
            Assert.assertEquals(0, keysWrong.size());
        }
    }