java中使用redis --- Hash的简单应用
1.java 代码
public class RedisTest01 {</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> main(String[] args) { </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> connect redis server</span> Jedis redis = <span style="color: rgba(0, 0, 255, 1)">new</span> Jedis("127.0.0.1", 6379<span style="color: rgba(0, 0, 0, 1)">); Map</span><String, String> map = <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> HashMap(); map.put(</span>"userName", "jack"<span style="color: rgba(0, 0, 0, 1)">); map.put(</span>"password", "123"<span style="color: rgba(0, 0, 0, 1)">); map.put(</span>"age", "12"<span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 将map存入redis中</span> redis.hmset("myMap"<span style="color: rgba(0, 0, 0, 1)">, map); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 取出redis中的map进行遍历</span> Map<String, String> userMap = redis.hgetAll("myMap"<span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 0, 255, 1)">for</span> (Map.Entry<String, String><span style="color: rgba(0, 0, 0, 1)"> item : userMap.entrySet()) { System.out.println(item.getKey() </span>+ " : " +<span style="color: rgba(0, 0, 0, 1)"> item.getValue()); } }
}
2. 输出
userName : jack
age : 12
password : 123
3.Hash 存储类型最适合存储 java 中的 Entity,用的比较多。。。