博客主页:我的主页
欢迎点赞 收藏 留言 欢迎讨论!
本文由 【泠青沼~】 原创,首发于 CSDN
由于博主是在学小白一枚,难免会有错误,有任何问题欢迎评论区留言指出,感激不尽!个人主页
目录
一、导入POM.xml配置文件 二、编写application.properties文件 三、分析RedisAutoConfiguration类 四、代码测试
4.1、存储对象键值对 4.2、存储字符串键值对 4.3、用字符串键值对存储对象
一、导入POM.xml配置文件REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统,Redis是一个开源的使用ANSI C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API,它通常被称为数据结构服务器,因为值(value)可以是 字符串(String), 哈希(Map), 列表(list), 集合(sets) 和 有序集合(sorted sets)等类型
二、编写application.properties文件org.springframework.boot spring-boot-starter-data-redis
spring.redis.host=127.0.0.1 spring.redis.port=6379 //如果你没有设置密码项就不填空着 spring.redis.password= 三、分析RedisAutoConfiguration类
@Bean @ConditionalOnMissingBean(name = "redisTemplate") @ConditionalOnSingleCandidate(RedisConnectionFactory.class) public RedisTemplate
四、代码测试 4.1、存储对象键值对这里主要使用RedisTemplate和stringRedisTemplate两个类用来redis的日常使用,所有的方法都集成在此类中,RedisTemplate可以存储带对象的键值对,而stringRedisTemplate只能存储字符串的键值对
@Test
void contextLoads() {
User user = new User();
user.setName("dong");
user.setPassword("123");
ValueOperations ops = redisTemplate.opsForValue();
ops.set("u",user);
User u = (User)ops.get("u");
System.out.println(u);
}
其中User必须要能自动序列化,加入实现接口Serializable
public class User implements Serializable {
private String name;
private String password;
4.2、存储字符串键值对
@Test
void contextLoads1() {
ValueOperations ops = stringRedisTemplate.opsForValue();
ops.set("djy","12345600");
String djy = ops.get("djy");
System.out.println(djy);
}
4.3、用字符串键值对存储对象
使用ObjectMapper对象进行序列化
@Test
void contextLoads2() throws JsonProcessingException {
ValueOperations ops = stringRedisTemplate.opsForValue();
User user = new User();
user.setName("wang");
user.setPassword("123123");
ObjectMapper om = new ObjectMapper();
String s = om.writevalueAsString(user);
ops.set("u",s);
String u = ops.get("u");
User user1 = om.readValue(u, User.class);
System.out.println(user1);
}



