Spring-整合redis
1创建Maven项目
2pom引入jar
<!-- 连接redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.4.RELEASE</version>
</dependency>
3Redis.conf
1.redis.conf 的配置
1)默认情况下redis运行在保护模式(这种模式下,访问不需要密码),但是这种模式只允许本地访问
protected-mode yes 改为 no
2)配置了只在127.0.0.1上绑定监听,取消一下
默认 bind 127.0.0.1 改为 #bind 127.0.0.1或 0.0.0.0
4关闭linux防火墙
Systemctl disable firewalld
Systectl stop firewalld
执行上面的命令,会永久关闭防火墙
5配置spring-redis.xml
<?xml version="1.0" encoding="UTF-8"?>
<!–3.1–注入工厂>
</bean>
</property>
</bean>
6常见序列化反序列化处理类
StringRedisSerializer 一般key的序列化使用
JdkSerializationRedisSerializer 默认的序列化方式
GenericJackson2JsonRedisSerializer
(选择) 支持对象转json,json转对象的序列和反序列化,支持带泛型的对象,效率比Jackson2JsonRedisSerializer低
Jackson2JsonRedisSerializer 支持对象转json,json转对象的序列和反序列化,不支持泛型,效率高
7测试运行
7.1测试存储String
7.1.1启动spring-redis并注入redisTemplate
7.1.2简单类型
@Test
public void test1() {//存储简单类型
ValueOperations<String,String> forValue = redisTemplate.opsForValue();
forValue.set(“name”, “张三”);//存入
System.out.println(forValue.get("address"));//获取
}
7.1.3 存储对象
@Test
public void test2() {
Student student = new Student(1,“王五”,19);
ValueOperations<String,Student> forValue = redisTemplate.opsForValue();
forValue.set(“stu1”, student);//存入
Student stu1 = forValue.get(“stu1”);//获取
System.out.println(stu1);
}
7.2存储list
7.2.1存储对象–单个存储
//存储list
@Test
public void testList() {
Student stu1 = new Student(1,“王五”,19);
Student stu2 = new Student(2,“赵六”,18);
Student stu3 = new Student(3,“田七”,20);
ListOperations<String,Student> opsForList = redisTemplate.opsForList();
//单个存储
opsForList.leftPush("students", stu1);
opsForList.leftPush("students", stu2);
opsForList.leftPush("students", stu3);
List<Student> list = opsForList.range("students", 0, -1);//获取整个students的集合
System.out.println(list);
}
7.2.2存储对象–集合存储
//存储list–存储集合
@Test
public void testList2() {
Student stu1 = new Student(1,“王五2”,19);
Student stu2 = new Student(2,“赵六2”,18);
Student stu3 = new Student(3,“田七2”,20);
ArrayList<Student> list2 = new ArrayList<Student>();
list2.add(stu1);
list2.add(stu2);
list2.add(stu3);
ListOperations<String,Student> opsForList = redisTemplate.opsForList();
//集合存储
opsForList.leftPushAll("studentList", list2);
// opsForList.leftPushAll("studentList", stu1,stu2,stu3);
List<Student> list = opsForList.range("studentList", 0, -1);//获取整个students的集合
System.out.println(list);
}
7.3存储hash
7.3.1存储单个
7.3.2存储集合
7.4Zset
7.5 Set