Redis_基础
Redis 命令启动、配置密码
Redis是绿色软件,所以直接解压就能使用
配置文件为:redis.windows.conf
启动redis 服务:
redis-server.exe redis.windows.conf
启动客户端:
redis-cli.exe
默认没有给Redis配置密码,所以在配置文件中配置密码
将密码设置为123456
# requirepass foobared改成
requirepass 123456
重新启动服务端,登录客户端的时候加上 -a 密码来登录;项目中就不用密码了
redis-server.exe redis.windows.conf -h localhost -p 6379 -a 123456
存放数据类型
Redis常用命令
String
SETEX为验证码场景
SETNX集群互斥
哈希
列表
集合
有序集合
通用命令
在Spring中使用Redis
导入坐标、配置数据源、配置类
redis实际上是创建了16个数据库,互相隔离;这里写索引为0-15
操作String类型数据
使用注入的RedisTemplate
注意代码中使用的函数不是以之前命令的名称进行命名的
我们之前使用了String的序列化器,那么在redis的客户端中,key是没有乱码的;但是值有乱码;
Hash操作
列表(list)类数据:
@Test
public void testList(){
//Lpush lrange rpop llen
ListOperations listOperations = redisTemplate.opsForList();
listOperations.leftPushAll("mylist","a","b","c"); //lpush多个value
listOperations.leftPush("mylist","d"); //lpush单个value
List mylist = listOperations.range("mylist",0,-1); //lrange
System.out.println(mylist);
listOperations.rightPop("mylist"); //rpop
Long size = listOperations.size("mylist"); //llen
System.out.println(size);
}
集合类数据:
@Test
public void testSet(){
//sadd smembers scard sinter sunion srem
SetOperations setOperations = redisTemplate.opsForSet();
setOperations.add("set1","a","b","c","d"); //sadd
setOperations.add("set2","a","b","x","y");
Set members = setOperations.members("set1"); //smembers
System.out.println(members);
Long size = setOperations.size("set1"); //scard
System.out.println(size);
Set intersect = setOperations.intersect("set1","set2"); //sinter取交集
System.out.println(intersect);
Set union = setOperations.union("set1","set2"); //sunion取并集
System.out.println(union);
setOperations.remove("set1","a","b"); //srem
}
有序集合类数据:
@Test
public void testZset(){
//zadd zrange zincrby zrem
ZSetOperations zSetOperations = redisTemplate.opsForZSet();
zSetOperations.add("zset1","a",10); //zadd
zSetOperations.add("zset2","b",12);
zSetOperations.add("zset1","c",9);
Set zset1 = zSetOperations.range("zset1",0,-1); //zrange
System.out.println(zset1);
zSetOperations.incrementScore("zset1","c",10); //zincrby
zSetOperations.remove("zset1","a","b"); //zrem
}
通用命令
@Test
public void testCommon(){
//keys exists type del
Set keys = redisTemplate.keys("*"); //keys
System.out.println(keys);
Boolean name = redisTemplate.hasKey("name"); //exists
Boolean set1 = redisTemplate.hasKey("set1");
for(Object key : keys){
DataType type = redisTemplate.type(key); //type
System.out.println(type.name());
}
redisTemplate.delete("mylist"); //del
}