ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] # 简介 redis中hashes类型可以看做具有String key和String value的map容器 ![](https://box.kancloud.cn/931ddf8b3c41756d3d43518f9a93298c_470x216.png) # 命令行 ![](https://box.kancloud.cn/b062f5407a7f2cbc45e964f62074ee2b_561x858.png) ![](https://box.kancloud.cn/1690da8a1cf09aec94ffe72b6dd14d39_512x596.png) ![](https://box.kancloud.cn/67fe1be5fea43ea4ca6e53af9dc0ff91_443x443.png) # 代码 ## 存数据 ~~~ @Test public void testHash() { Jedis jedis = init(); //如果里面没有,那返回值是1,有返回值是0 Long a1 = jedis.hset("cart:user02", "书", "高性能mysql-2"); Long a2 = jedis.hset("cart:user02", "笔", "圆珠笔"); Long a3 = jedis.hset("cart:user02", "画", "八骏图"); jedis.close(); } ~~~ ~~~ jedis.hset("testHash", "counrty", "china");//向testHash表里添加一条记录 Map<String,String> data = new HashMap<String, String>(); data.put("sex", "man"); data.put("add", "nibo"); jedis.hmset("testHash", data);//向testHash表里添加多条记录 ~~~ ## 修改 ~~~ jedis.hset("testHash", "counrty", "china1");//直接覆盖值 jedis.hset("testHash", "age", "999");//直接覆盖值 jedis.hincrBy("testHash", "age", 1);//增加指定值 ~~~ ## 查询 ~~~ @Test public void testSelect() { Jedis jedis = init(); Map<String, String> hgetAll = jedis.hgetAll("cart:user02"); Set<Map.Entry<String, String>> entrySet = hgetAll.entrySet(); for (Map.Entry<String, String> entry : entrySet) { System.out.println(entry.getKey() + ":" + entry.getValue()); } } ~~~ ~~~ //查找指定hash的指定key jedis.hget("testHash", "counrty"); ~~~ ## 自增 ~~~ Jedis jedis = init(); jedis.hset("cart:user", "价格1", "1"); jedis.hset("cart:user", "价格2", "1"); //给价格1的值+1 jedis.hincrBy("cart:user", "价格1", 1); jedis.close(); ~~~ ## 删除 ~~~ Jedis jedis = init(); jedis.hdel("testHash", "counrty");//删除单条记录 jedis.hdel("testHash", "counrty","age");//删除多条记录,没有就忽略 jedis.close(); ~~~ ## 扩展 ~~~ //扩展命令 jedis.hexists("testHash", "counrty");//判断testHash表里是否存在key是counrty的元素 jedis.hlen("testHash"); //表长度 jedis.hkeys("testHash");//获得所有keys jedis.hvals("testHash");//获得所有values ~~~