Spring Data Redis
简介
网址:https://spring.io/projects/spring-data-redis
Spring Data Redis中提供了一个高度封装的类:RedisTemplate,对相关api进行了归类封装,将同一类型操作封装为operation接口,具体分类如下:
- ValueOperations:string数据操作
- SetOperations:set类型数据操作
- ZSetOperations:zset类型数据操作
- HashOperations:hash类型的数据操作
- ListOperations:list类型的数据操作
环境搭建
导入maven坐标
初始项目结构已经搭建好
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置Redis数据源
在application-dev.yml中添加
sky:redis:host: localhostport: 6379password: 123456database: 10
解释说明:
database:指定使用Redis的哪个数据库,Redis服务启动后默认有16个数据库,编号分别是从0到15。如果不在yml文件中指定该参数,默认使用的是DB0。
在application.yml中添加读取application-dev.yml中的相关Redis配置
spring:profiles:active: devredis:host: ${sky.redis.host}port: ${sky.redis.port}password: ${sky.redis.password}database: ${sky.redis.database}
编写配置类,创建RedisTemplate对象
package com.sky.config;import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
@Slf4j
public class RedisConfiguration {@Bean//形参中的连接工厂对象实际上并不需要我们手动传入,因为我们引入了starter,它会自动帮我们传入的。public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){log.info("开始创建redis模板对象");RedisTemplate redisTemplate = new RedisTemplate();//设置redis的连接工厂对象redisTemplate.setConnectionFactory(redisConnectionFactory);//设置redis key的序列化器,否则java传过去的数据存储到redis里面会是一串二进制数或者其他格式的数。//因为这里只设置了key的序列化器,后续测试时可以看到field和value显示的值不一定是java传过去的值。redisTemplate.setKeySerializer(new StringRedisSerializer());return redisTemplate;}
}
解释说明:
当前配置类不是必须的,因为 Spring Boot 框架会自动装配 RedisTemplate 对象,但是默认的key序列化器为JdkSerializationRedisSerializer,导致我们存到Redis中后的数据和原始数据有差别,故设置为StringRedisSerializer序列化器。
且形参的连接工厂对象报红报错是正常的,暂时先别管。
通过RedisTemplate对象操作Redis
在test下新建测试类
package com.sky.test;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;@SpringBootTest
public class SpringDataRedisTest {@Autowiredprivate RedisTemplate redisTemplate;@Testpublic void testRedisTemplate(){System.out.println(redisTemplate);//string数据操作ValueOperations valueOperations = redisTemplate.opsForValue();//hash类型的数据操作HashOperations hashOperations = redisTemplate.opsForHash();//list类型的数据操作ListOperations listOperations = redisTemplate.opsForList();//set类型数据操作SetOperations setOperations = redisTemplate.opsForSet();//zset类型数据操作ZSetOperations zSetOperations = redisTemplate.opsForZSet();}
}
编写测试方法
测试字符串
@Testpublic void testString(){// 相当于redis中的set city 背景redisTemplate.opsForValue().set("city", "北京");// 相当于redis中的get cityString city = (String) redisTemplate.opsForValue().get("city");System.out.println(city);// 相当于redis中的setex code 180 1234 因为这里是3分钟,redis中的setex语句默认是秒,所以是180秒redisTemplate.opsForValue().set("code","1234",3, TimeUnit.MINUTES);// 相当于setnx lock 1和setnx lock 2redisTemplate.opsForValue().setIfAbsent("lock","1");redisTemplate.opsForValue().setIfAbsent("lock","2");}
测试哈希
@Testpublic void testHash(){HashOperations hashOperations = redisTemplate.opsForHash();// 相当于redis中的hset 100 name tomhashOperations.put("100","name","tom");hashOperations.put("100","age","20");// 相当于redis中的hget 100 nameString name = (String) hashOperations.get("100", "name");System.out.println(name);//相当于redis中的hkeys 100Set keys = hashOperations.keys("100");System.out.println(keys);//相当于redis中的hvals 100List values = hashOperations.values("100");System.out.println(values);//相当于redis中的hdel 100 agehashOperations.delete("100","age");}
测试列表
/*** 操作列表类型的数据*/@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);}
测试集合
/*** 操作集合类型的数据*/@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");}
测试有序列表
/*** 操作有序集合类型的数据*/@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");}
测试通用
/*** 通用命令操作*/@Testpublic 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");}