SpringBoot整合Redis之RedisTemplate
java连接redis(jedis)
spring-data-redis针对jedis提供了如下功能:
1.连接池自动管理,提供了一个高度封装的“RedisTemplate”类
2.针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口
ValueOperations:简单K-V操作 String
SetOperations:set类型数据操作
ZSetOperations:zset类型数据操作
HashOperations:针对map类型的数据操作
ListOperations:针对list类型的数据操作
spring-data-redis:lettuce
(一)创建SpringBoot程序引入启动器
或者是pom.xml文件当中引入启动器依赖
<!--整合redis的启动器-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
(二)application.yml配置连接信息
spring:
redis:
host: 192.168.126.10
port: 6379
password: 123456
(三)使用RedisTemplate操作Redis
1 值类型操作
@SpringBootTest //springboot的测试环境
class SpringbootredisApplicationTests {
@Resource
private RedisTemplate<String,String> redisTemplate;
//操作String类型 ops---Operations for Value
@Test
void test1() {
ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
//存
opsForValue.set("myredis","hello redis");
//取
String myredis = opsForValue.get("myredis");
System.out.println(myredis);
}
//
@Test
void test2() {
ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
//不管是什么数据型(String,set,hash,list,zset)删除都使用redisTemplate.delete()
redisTemplate.delete("myredis");
}
}
2 Set类型操作
//set
@Test
void test3() {
SetOperations<String, String> opsForSet = redisTemplate.opsForSet();
//存
opsForSet.add("studentSet","jack","tomer","xixi","jojo");
//取
Set<String> studentSet = opsForSet.members("studentSet");
System.out.println(studentSet);
}
//set 移除单个元素
@Test
void test4() {
SetOperations<String, String> opsForSet = redisTemplate.opsForSet();
opsForSet.remove("studentSet","tomer");
}
//删除整个set
@Test
void test5() {
SetOperations<String, String> opsForSet = redisTemplate.opsForSet();
redisTemplate.delete("studentSet");
}
3 List集合操作
3.1 右压栈
// 右压栈
@Test
void test3() {
ListOperations<String, String> ops = redisTemplate.opsForList();
//右压栈 元素可以重复
ops.rightPush("myList","a");
ops.rightPush("myList","b");
ops.rightPush("myList","c");
ops.rightPush("myList","c");
ops.rightPush("myList","c");
ops.rightPush("myList","c");
//一次性添加
opsForList.rightPushAll("studentlist","kaka","jojo","yuyu","roro");
//取值:
List<String> myList = ops.range("myList", 0, -1);
System.out.println(myList);
}
3.2 左压栈
// 左压栈
@Test
void test4() {
ListOperations<String, String> ops = redisTemplate.opsForList();
//左压栈
ops.leftPush("myList","A");
ops.leftPush("myList","B");
ops.leftPush("myList","C");
//一次添加
opsForList.rightPushAll("studentlist2","kaka","jojo","yuyu","roro");
//取值:
List<String> myList = ops.range("myList", 0, -1);// CBAabc
System.out.println(myList);
}
3.3 根据索引查询元素
// 根据索引查询元素
@Test
void test5() {
ListOperations<String, String> ops = redisTemplate.opsForList();
String value = ops.index("myList", 1);
System.out.println(value);
}
3.4 移除某个元素的值
// 移除某个元素的值
@Test
void test6() {
ListOperations<String, String> ops = redisTemplate.opsForList();
ops.remove("myList",1,"A");
List<String> myList = ops.range("myList", 0, -1);//
System.out.println(myList);// CBabc
}
4 Hash类型操作
4.1 存入值
@Test
void demo5() {
HashOperations<String, String, String> opsForHash = redisTemplate.opsForHash();
opsForHash.put("user","u1","jack");
opsForHash.put("user","u2","tomer");
opsForHash.put("user","u3","xixi");
Map<String,String> map=new HashMap<>();
map.put("s1","jack");
map.put("s2","haha");
opsForHash.putAll("stuList",map);
}
4.2 提取所有的KEY
// 提取所有的KEY
@Test
void test8() {
HashOperations<String, Object, Object> ops = redisTemplate.opsForHash();
// 提取所有的KEY[field]
Set<Object> user = ops.keys("user");
System.out.println(user);// username address age
}
4.3 提取所有的值
// 提取所有的值
@Test
void test9() {
HashOperations<String, Object, Object> ops = redisTemplate.opsForHash();
// 提取所有的KEY[field]
List<Object> user = ops.values("user");
System.out.println(user);
}
4.4 根据KEY提取值
// 根据KEY提取值
@Test
void test10() {
HashOperations<String, Object, Object> ops = redisTemplate.opsForHash();
// 提取所有的KEY[field]
String o = (String) ops.get("user", "username");
System.out.println(o);
}
4.5根据KEY移除值
// 根据KEY移除值
@Test
void test11() {
HashOperations<String, Object, Object> ops = redisTemplate.opsForHash();
// 提取所有的KEY[field]
ops.delete("user", "username");
}
4.5获取key=value
@Test
void test12() {
HashOperations<String, Object, Object> ops = redisTemplate.opsForHash();
Map<Object, Object> userList = opsForHash.entries("userList");
System.out.println(userList);
}
(四)SpringBoot整合Redis序列化操作
存对象
1/新建实体类
public class Person implements Serializable{
private Integer id;
private String name;
private String address;
}
2、新建测试类
@SpringBootTest
class SpringbootredisApplicationTestsTeo {
//泛型是person
@Resource
private RedisTemplate<String, Person> redisTemplate;
@Test
void persontest(){
Person person=new Person(1,"jack","fdsafdsafdsafdsaf");
ValueOperations<String, Person> opsForValue = redisTemplate.opsForValue();
//存对象
opsForValue.set(person.getName(),person);
//取对象
//Person person1 = opsForValue.get(person.getName());
//System.out.println(person1);
}
}
能正常存与取,只是我们在redis客端查看内容,感觉内容【像是】乱码
为什么会这样子:
1 Spring提供的序列化器介绍
1.1 Spring默认序列化器
RedisTemplate操作时,默认会采用jdkSerializable序列化机制,使得插入的值在redis客户端看来会有乱码,若想解决这一问题,需要手动指定序列化方式。
public class RedisTemplate<K, V> extends RedisAccessor implements RedisOperations<K, V>, BeanClassLoaderAware {
public void afterPropertiesSet() {
super.afterPropertiesSet();
boolean defaultUsed = false;
if (this.defaultSerializer == null) {
this.defaultSerializer = new JdkSerializationRedisSerializer(this.classLoader != null ? this.classLoader : this.getClass().getClassLoader());
}
...
}
1.2 常见的序列化器
2 序列化案例实现
2.1添加依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
2.1 新建配置类并设置序列化器
@Configuration
public class MyConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
// 将刚才的redis连接工厂设置到模板类中
template.setConnectionFactory(redisConnectionFactory);
// 设置key的序列化器
template.setKeySerializer(new StringRedisSerializer());
// 设置value的序列化器
//使用Jackson 2,将对象序列化为JSON
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//json转对象类,不设置默认的会将json转成hashmap
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
return template;
}
}