世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。
String操作:
// 连接客户端
./redis-cli -h 127.0.0.1 -p 6379
// 设置键值对,返回ok
set hello good
// 设置键值对同时设置过期时间,ex为秒,ps为毫秒,返回ok
set hello good ex|px 10
// key不存在则设置key的值
setnx hello good
// 设置多个键值对
mset hello good he good key good key1 good
// 不存在则设置,有一个存在即失败,所有的都不会设置
msetnx hello me key2 me key3 me key4 me
// 从offset开始覆盖值
setrange hello 2(offset) kkk(覆盖的value)
// 根据键获取值
get hello
// 设置新值,返回旧值
getset hello goo
// 获取多个key的值
mget key1 key2 key3
// 键的数字值加1,返回增加后的结果
incr num
// 键的数字值加一定值,返回增加后的结果
incrby num 3
// 增加浮点值,但是再进行整数值操作时就会报错
incrbyfloat num 3.3
// 数值减1
decr num
// 数值减一定值
decrby num 3
// 获取字符串的长度
strlen key1
// 根据键删除键值对,返回实际删除的键值对的个数
del hello
// 删除多个键值对,返回实际删除的键值对的个数
del key1 key2 key3
// 查看键是否存在,返回实际存在的键值对的个数
exists hello
// 查看多个键是否存在,返回实际存在的键值对的个数
exists hello key1 key2
// 根据键拼接值,返回拼接后值的长度
append hello good
// 根据键以及值的下标获取值的某一部分
getrange hello 0 3
// 设置过期时间,返回1
expire hello 3
// 设置过期时间,单位毫秒
pexpire hello 2000
// 设置过期时间,单位timestamp
expireat hello 2000
// 设置过期时间,单位timestamp
pexpireat hello 2000
// 查看距离当前剩余的过期时间,如果已过期返回-2,如果不存在返回-1,秒
ttl hello
// 剩余过期时间,毫秒
pttl hello
// 根据键返回值的类型
type hello
// 序列化key,并返回被序列化的值
dump hello
// 查看所有键
keys *
// 键重命名
rename hello he
// new键不存在时,将键改为new键
renamenx hello he
// 根据游标获取键
scan 0
// 随机返回一个key
randomkey
String的Template操作:
@Autowired
StringRedisTemplate template;
@Test
public void test1(){
int ini = 16;
ValueOperations<String, String> valueOpt = template.opsForValue();
// 设置键值对
valueOpt.set("hello", "me");
// 获取键的值
print(valueOpt.get("hello"));
// 设置键值对过期时间
valueOpt.set("hello", "kkk", 3, TimeUnit.SECONDS);
print(valueOpt.get("hello"));
// 如果键值对不存在则设置,如果存在则不设置
valueOpt.setIfAbsent("kill", "kill you");
print(valueOpt.get("kill"));
// 同时设置多个键值对
Map<String, String> map = new HashMap<>(ini);
map.put("k1", "v1");
map.put("k2", "v2");
map.put("k3", "v3");
valueOpt.multiSet(map);
// 同时获取多个键的值
print(valueOpt.multiGet(Arrays.asList("k1", "k2", "k3")));
// 如果不存在,则设置多个键值对的值,注意其中有一个存在的,其他不存在的也不会设置
map = new HashMap<>(ini);
map.put("k4", "v41");
map.put("k5", "v5");
map.put("k6", "v6");
map.put("k7", "v7");
valueOpt.multiSetIfAbsent(map);
print(valueOpt.multiGet(Arrays.asList("k4", "k5", "k6", "k7")));
// 根据offset覆盖值
valueOpt.set("hello", "ttt", 1);
print(valueOpt.get("hello"));
// 获取旧值并设置新值
print(valueOpt.getAndSet("hello", "me"));
print(valueOpt.get("hello"));
// 整数值加1
print(valueOpt.increment("incr1"));
// 整数值加3
print(valueOpt.increment("incr2", 3));
// 加float值
print(valueOpt.increment("incr3", 5.5));
// 整数值-1
print(valueOpt.decrement("incr2"));
// 整数值-2
print(valueOpt.decrement("incr2", 2));
// 获取指定下标范围的值
print(valueOpt.get("hello", 1, 2));
// 对值进行append追加
print(valueOpt.append("hello", "hekkelw"));
print(valueOpt.get("hello"));
// 获取值的大小
print(valueOpt.size("hello"));
}