redis 通过value获得key值

package cn.theone.tmp;

import cn.theone.tmp.dictionary.pageModel.Mdictionary;
import cn.theone.tmp.redis.util.RedisHashUtil;
import cn.theone.tmp.redis.util.RedisListUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Calendar;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TmpApplicationRedisTest {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void contextLoads() {
    //添加两条数据到redis中
    redisTemplate.opsForHash().put("xwyj:mdeptMap","100000000000","应急管理局");
    redisTemplate.opsForHash().put("xwyj:mdeptMap","100000000001","交警大队");

	//通过外层key拿到下面的对象,外层key一般都是已知的
	Map<Object, Object> entries = redisTemplate.opsForHash().entries("xwyj:mdeptMap");
    	
    //假设该变量就是前端传来的value
    String valueName= "应急管理局";

	//遍历缓存对象
	for (Object value : entries.keySet()) {
			//如果value是对象直接强转对象即可
            String o = (String) entries.get(value);
            //字符串在缓存中取出来有的时候会多出一对双引号,可以debug看一下,把引号去掉
            o = o.replace("\"", "");
            //用假设前端的value和对象下的value相比较,相同则取出对应key即可
            if (valueName.equals(o)) {
                System.out.println(value);
            }
        }
    }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
这里简单的redis用value找key就可以了,有问题可以指出!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐