数据类型详解
在讲解Redis中List的使用之前,大家需要知道List是怎么样的结构,方便在合适的场景中去使用。
String类型是redis中属于最简单的一个,就是一个Key对应一个value,value中可以接受任意格式的数据(JSON、图片)但是最多能容纳数据长度是512M
这个我在之前的博客也有讲过,各位看官老爷可以移步到这篇博客
结构类型:双向链表
操作命令
-添加
127.0.0.1:6379[2]> help set
SET key value [EX seconds] [PX milliseconds] [NX|XX]
summary: Set the string value of a kmey(设置String的key)
since: 1.0.0
group: string
127.0.0.1:6379[2]> help SETNX
SETNX key value
summary: Set the value of a key, only if the key does not exist(只有当key不存在的时候设置key)
since: 1.0.0
group: string
127.0.0.1:6379[2]> help mset
MSET key value [key value ...]
summary: Set multiple keys to multiple values(批量设置value值)
since: 1.0.1
group: string
使用set的时候,如果没有key就添加key,如果有key那么就覆盖。
-追加
127.0.0.1:6379[2]> help append
APPEND key value
summary: Append a value to a key(在key后面直接添加字符,成功返回v的长度)
since: 2.0.0
group: string
-自增
127.0.0.1:6379[2]> help INCR
INCR key
summary: Increment the integer value of a key by one(v每次自增1)
since: 1.0.0
group: string
127.0.0.1:6379[2]> help INCRBY
INCRBY key increment
summary: Increment the integer value of a key by the given amount(v按照指定的数值进行增长)
since: 1.0.0
group: string
只有在v是数值的情况下才可以实现增加,增加成功之后,返回成功后的值,如果v不为数值则报错
-查看
127.0.0.1:6379[2]> help get
GET key
summary: Get the value of a key(查看key下的v)
since: 1.0.0
group: string
127.0.0.1:6379[2]> help mget
MGET key [key ...]
summary: Get the values of all the given keys(查看多个key下的v)
since: 1.0.0
group: string
批量查看的时候v的值按照key输入的顺序输出
127.0.0.1:6379[2]> help STRLEN
STRLEN key
summary: Get the length of the value stored in a key(获取指定k下的v的长度)
since: 2.2.0
group: string
127.0.0.1:6379[2]> help GETRANGE
GETRANGE key start end
summary: Get a substring of the string stored at a key(获取指定k下的开始到结束的字符串)
since: 2.4.0
group: string
使用
下面是在java代码中具体使用过程
String类型应该是平常使用最多的类型
// 查找匹配的key值,返回set集合
redisTemplate.opsForValue().set("a", 12345);
// 返回部分字符
System.out.println(redisTemplate.opsForValue().get("a", 4, 6));
// 5
// 获取字符串的长度
System.out.println(redisTemplate.opsForValue().size("a"));
// 5
//批量添加
HashMap<Object, Object> hashMap = new HashMap<>();
hashMap.put("a","100");
hashMap.put("b","200");
hashMap.put("c","300");
redisTemplate.opsForValue().multiSet(hashMap);
// 批量获取值
List keys2 = new ArrayList();
keys2.add("a");
keys2.add("b");
keys2.add("c");
System.out.println(redisTemplate.opsForValue().multiGet(keys2));
// [100, 200, 300]
// 重新设置key对应的值,如果存在返回false,否则返回true
redisTemplate.opsForValue().setIfAbsent("a", 54321);
System.out.println(redisTemplate.opsForValue().get("a"));
// 12345