Redis5种常用的数据类型
Redis字符串String
Redis哈希hash
Redis列表
Redis集合
Redis有序集合
Redis通用命令
SpringDataRedis
String类型
redisTemplate.opsForValue().set("city", "NanChang");
String cityName = (String) redisTemplate.opsForValue().get("city");
System.out.println(cityName);
redisTemplate.opsForValue().set("city2", "JiAn", 10L, TimeUnit.SECONDS);//设置过期时间
Boolean b = redisTemplate.opsForValue().setIfAbsent("city", "Beijing");//如果key不存在再创建
System.out.println(Boolean.TRUE.equals(b) ? "操作成功" : "操作失败");
hash类型
HashOperations hashOperations = redisTemplate.opsForHash();
//存值
hashOperations.put("002", "name", "黄乘明");
hashOperations.put("002", "age", "21");
hashOperations.put("002", "address", "南昌");
//取值
String name = (String) hashOperations.get("002", "name");
System.out.println(name);
//获取hash字段中的所有field
Set keys = hashOperations.keys("002");
for (Object key : keys) {
System.out.println(key);
}
//获取hash结构中所有的value
List values = hashOperations.values("002");
for (Object value : values) {
System.out.println(value);
}
列表类型
ListOperations listOperations = redisTemplate.opsForList();
//存值
listOperations.leftPush("myList", "a");
listOperations.leftPushAll("myList", "b", "c", "d");
//取值
List<String> myList = listOperations.range("myList", 0, -1);
for (String s : myList) {
System.out.println(s);
}
//获取列表长度
Long size = listOperations.size("myList");
int intSize = size.intValue();
//出队列
for (int i = 0; i < intSize; i++) {
String element = (String) listOperations.rightPop("myList");
System.out.println(element + "已退出队列");
}
操作set
SetOperations setOperations = redisTemplate.opsForSet();
//填入数据
setOperations.add("mySet", "a", "b", "c", "a");
//取值
Set<String> mySet = setOperations.members("mySet");
for (String s : mySet) {
System.out.println(s);
}
//删除成员
setOperations.remove("mySet","a", "b");
ZSet
ZSetOperations zSetOperations = redisTemplate.opsForZSet();
//添加数据
zSetOperations.add("game", "hcm", 10.0);
zSetOperations.add("game", "ywh", 11.0);
zSetOperations.add("game", "lzh", 9.6);
zSetOperations.add("game", "wh", 100.0);
//查看数据
Set<String> game = zSetOperations.range("game", 0, -1);
for (String s : game) {
System.out.println(s);
}
//修改分数
zSetOperations.incrementScore("game", "hcm", 0.1);
//查看数据
game = zSetOperations.range("game", 0, -1);
for (String s : game) {
System.out.println(s);
}
//移除元素
zSetOperations.remove("game", "hcm", "lzh");
//查看数据
game = zSetOperations.range("game", 0, -1);
for (String s : game) {
System.out.println(s);
}
通用操作
//获取redis中所有的key
Set<String> keys = redisTemplate.keys("*");
for (String key : keys) {
System.out.println(key);
}
//判断某个key是否存在
Boolean b = redisTemplate.hasKey("city");
System.out.println(b);
//删除指定key
redisTemplate.delete("game");
//获取某个key对应的数据类型
DataType mySet = redisTemplate.type("mySet");
System.out.println(mySet.name());