redis在java中的使用
Redis是一个基于内存的key-value结构数据库,spring data redis是spring的一部分,对redis底层开发包进行了封装,可以直接使用Spring Data Redis简化操作。
5种常见的数据类型
Redis中key是字符串类型,value有5种常用数据类型:
- 字符串 string
- 哈希 hash
- 列表 list (按插入顺序排序,可以从左往右插入,也可以从右往左插入)
- 集合 set (没有重复元素)
- 有序集合 sorted set / zset (没有重复元素)
Spring Data Redis使用方式
-
导入Spring Data Redis的maven坐标
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
-
配置Redis数据源
spring:profiles:active: devmain:allow-circular-references: truedatasource:druid:driver-class-name: ${sky.datasource.driver-class-name}url: jdbc:mysql://${sky.datasource.host}:${sky.datasource.port}/${sky.datasource.database}?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=trueusername: ${sky.datasource.username}password: ${sky.datasource.password}redis:host: ${sky.redis.host}port: ${sky.redis.port}password: ${sky.redis.password}database: ${sky.redis.database}
-
编写配置类,创建RedisTemplate对象
@Configuration @Slf4j public class RedisConfiguration {public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){log.info("开始创建redis模板对象。。。");RedisTemplate redisTemplate = new RedisTemplate();//设置redis的连接工厂对象redisTemplate.setConnectionFactory(redisConnectionFactory);//设置redis key的序列化器redisTemplate.setKeySerializer(new StringRedisSerializer());return redisTemplate;} }
-
通过RedisTemplate对象操作Redis
private RedisTemplate redisTemplate;public void testRedisTemplate(){System.out.println(redisTemplate);ValueOperations valueOperations = redisTemplate.opsForValue();HashOperations hashOperations = redisTemplate.opsForHash();ListOperations listOperations = redisTemplate.opsForList();SetOperations setOperations = redisTemplate.opsForSet();ZSetOperations zSetOperations = redisTemplate.opsForZSet(); }
Redis常用命令及在Spring Data Redis中相应的操作
字符串操作命令
- SET key value 设置指定key的值
- GET value
- SETEX key seconds value 设置指定key的值,并将key的过期时间设置为seconds秒
- SETNX key value 只有在key不存在的时候设置key的值
使用Spring Data Redis操作Redis字符串:
/*** 操作字符串类型的数据*/@Testpublic void testString(){// set get setex setnxredisTemplate.opsForValue().set("name","小明");String city = (String) redisTemplate.opsForValue().get("name");System.out.println(city);redisTemplate.opsForValue().set("code","1234",3, TimeUnit.MINUTES);redisTemplate.opsForValue().setIfAbsent("lock","1");redisTemplate.opsForValue().setIfAbsent("lock","2");}
哈希操作命令
hash特别适合存储对象,常用命令:
- HSET key field(字段) value 将哈希表key中的字段field的值设置为value
- HGET key field
- HDEL key field
- HKEYS key 获取哈希表中所有的字段
- HVALS key 获取哈希表中所有的值
使用Spring Data Redis操作Redis哈希表:
/*** 操作哈希类型的数据*/@Testpublic void testHash(){//hset hget hdel hkeys hvalsHashOperations hashOperations = redisTemplate.opsForHash();hashOperations.put("100","name","tom");hashOperations.put("100","age","20");String name = (String) hashOperations.get("100", "name");System.out.println(name);Set keys = hashOperations.keys("100");System.out.println(keys);List values = hashOperations.values("100");System.out.println(values);hashOperations.delete("100","age");}
列表操作命令
-
LPUSH key value1 [value2] 将一个或者多个值插入列表头部
-
LRANGE key start stop 获取列表指定范围的元素
-
RPOP key 移除并获取列表最后一个元素
-
LLEN key 获取列表长度
使用Spring Data Redis操作Redis列表:
/*** 操作列表类型的数据*/@Testpublic void testList(){//lpush lrange rpop llenListOperations listOperations = redisTemplate.opsForList();listOperations.leftPushAll("mylist","a","b","c");listOperations.leftPush("mylist","d");List mylist = listOperations.range("mylist", 0, -1);System.out.println(mylist);listOperations.rightPop("mylist");Long size = listOperations.size("mylist");System.out.println(size);}
集合操作命令
- Redis set是string类型的无序集合,且集合成员是唯一的
- SADD key member1 [member2]
- SMEMBERS key 返回集合中的所有成员
- SCARD key 获取集合的成员数
- SINTER key1 [key2] 返回给定所有集合的交集
- SUNION key1 [key2] 返回所有给定集合的并集
- SREM key member1 [member2] 删除集合中一个或多个成员
使用Spring Data Redis操作Redis集合:
/*** 操作集合类型的数据*/@Testpublic void testSet(){//sadd smembers scard sinter sunion sremSetOperations setOperations = redisTemplate.opsForSet();setOperations.add("set1","a","b","c","d");setOperations.add("set2","a","b","x","y");Set members = setOperations.members("set1");System.out.println(members);Long size = setOperations.size("set1");System.out.println(size);Set intersect = setOperations.intersect("set1", "set2");System.out.println(intersect);Set union = setOperations.union("set1", "set2");System.out.println(union);setOperations.remove("set1","a","b");}
有序集合操作命令
Redis zset是string类型的有序集合,且集合成员是唯一的,与无序集合不同的是,有序集合的每个元素都会关联一个double类型的分数。常用命令:
- ZADD key score1 member1 [score2 member2]
- ZRANGE key start stop [WITHSCORES] 通过索引区间返回有序集合中指定区间内的成员[跟上WITHSCORES参数,会将分数值也返回]
- ZINCRBY key increment member 有序集合中对指定成员的分数加上增量 increment
- ZERM key member [member] 移除有序集合中的一个或多个成员
使用Spring Data Redis操作Redis有序集合:
/*** 操作有序集合类型的数据*/@Testpublic void testZset(){//zadd zrange zincrby zremZSetOperations zSetOperations = redisTemplate.opsForZSet();zSetOperations.add("zset1","a",10);zSetOperations.add("zset1","b",12);zSetOperations.add("zset1","c",9);Set zset1 = zSetOperations.range("zset1", 0, -1);//返回所有元素System.out.println(zset1);zSetOperations.incrementScore("zset1","c",10);zSetOperations.remove("zset1","a","b");}
通用命令
- KEYS pattern 查找所有符合给定模式的key(比如 KEYS * 是查找所有的key返回 KEYS set*是返回所有以set开头的key)
- EXISTS key 查找给定key是否存在
- TYPE key 返回key所存储的值的类型
- DEL key 存在key时删除key
public void testCommon(){//keys exists type delSet keys = redisTemplate.keys("*");System.out.println(keys);Boolean name = redisTemplate.hasKey("name");Boolean set1 = redisTemplate.hasKey("set1");for (Object key : keys) {DataType type = redisTemplate.type(key);System.out.println(type.name());}redisTemplate.delete("mylist");}