springboot操作redis
底层注意点
springboot2.x版本之后,原来使用的jedis被替换成了lettuce
jedis:采用的直连,多个线程操作的话是不安全的,如果想要避免不安全的,需要使用jedis pool连接池~ 更像BIO模式
lettuce:采用netty,实例可以在多个线程中进行共享,不存在线程不安全的情况!,可以减少线程数据~ 更像NIO模式
依赖添加
<!--redis启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
基本配置
spring:
redis:
host: 127.0.0.1
username:
password:
port: 6379
database: 0
测试
@SpringBootTest
class StudyApplicationTests {
//获取redis的bean
@Autowired
private RedisTemplate redisTemplate;
@Test
void contextLoads() throws SQLException {
//获取redis的连接对象
// RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
// connection.flushAll(); //清空所有库
// connection.flushDb(); //情况当前库
// redisTemplate.opsForValue() 操作字符串
// redisTemplate.opsForGeo() 操作地理位置
// redisTemplate.opsForHash() 操作map,其他set、zet一致
//获取对象后所有的语法和基本命令一致
redisTemplate.opsForValue().set("name","魔尊");
Object name = redisTemplate.opsForValue().get("name");
System.out.println(name);
}
}
存值注意点
Student stu = new Student();
stu.setStuId("fsdfsdfsdfsd");
stu.setStuName("魔尊");
stu.setStuSex(0);
stu.setStuAge(18);
redisTemplate.opsForValue().set("user",stu);
Object name = redisTemplate.opsForValue().get("user");
System.out.println(name);
//以上代码直接将未序列化的对象直接进行存储,会爆以下错误,《需要序列化》
Caused by: java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.lwp.study.pojo.Student]
//序列化方式1 ==>使用jackjson的ObjectMapper实现序列化
import com.fasterxml.jackson.databind.ObjectMapper;
new ObjectMapper().writeValueAsString(stu)
//序列化方式2 ==》类实现Serializable
public class Student implements Serializable {}