SpringDataRedis快速入门

SpringDataRedis

什么是SpringDataRedis

SpringData是Spring中数据操作的模块,包含对各种数据库的集成,其中对Redis的集成模块就叫做SpringDataRedis

SpringDataRedis中提供了RedsiTemplate工具类,其中封装了各种对Redis的操作。并且将不同数据类型的操作API封装到了不同的类中

基于SpringBoot使用

1.引入依赖

复制代码
  <!--添加 redis 依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2.配置yml文件

复制代码
spring:
  redis:
    host: 你的虚拟机ip
    port: 端口号
    password: 你的redis密码
    lettuce:
      pool:
        max-active: 8 #最大连接
        max-idle: 8 #最大空闲连接
        min-idle: 0 #最小空闲连接
        max-wait: 100ms #连接等待时间

3.注入RedisTemolate

java 复制代码
 @Autowired
    RedisTemplate redisTemplate;

4.编写测试

java 复制代码
@SpringBootTest
public class RedisDemoApplicationTests {

    @Autowired
    RedisTemplate redisTemplate;

    @Test
    void Test(){
        //写入一条String数据
        redisTemplate.opsForValue().set("name","你好");
        //获取String数据
        Object res = redisTemplate.opsForValue().get("name");
        System.out.println(res);
    }
}

redistemplate默认将key和value当作java对象,会自动将key和value序列化

我们可以自定义RedisTemplate的序列化方式

java 复制代码
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory connectionFactory){
        //创建RedisTemplate对象
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //设置连接工厂
        template.setConnectionFactory(connectionFactory);
        //创建JSON序列化工具
        GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        //设置Key的序列化
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        //设置Value的序列化
        template.setValueSerializer(jsonRedisSerializer);
        template.setHashKeySerializer(jsonRedisSerializer);
        //返回
        return template;
    }
}

为了节省内存空间,我们不会使用JSON序列化器来处理value,而是统一使用String序列化器,要求只能存储String类型的key和value。当要存储Java对象时,手动完成对对象的序列化和反序列化

Spring默认提供了一个StringRedisTemplate类,它的key和value的序列化方式默认就是String方式。省去了我们自己定义RedisTemplate的过程:

java 复制代码
@SpringBootTest
public class RedisStringTest {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    //JSON工具
    private static final ObjectMapper mapper = new ObjectMapper();

    @Test
    void testUser() throws JsonProcessingException {
        User user = new User("小张",16);
        //将对象序列化后存入
        stringRedisTemplate.opsForValue().set("user1", mapper.writeValueAsString(user));
        String user1 = stringRedisTemplate.opsForValue().get("user1");
        //将取出的字符串反序列化
        User user2 = mapper.readValue(user1, User.class);
        System.out.println(user2.getName()+":"+user2.getAge());
    }
}

使用hash类型

java 复制代码
@Test
    void testHash(){
        stringRedisTemplate.opsForHash().put("user:200","name","小张");
        stringRedisTemplate.opsForHash().put("user:200","age","16");
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries("user:200");
        System.out.println(entries);
    }
相关推荐
qq_12498707535 小时前
基于springboot健康养老APP的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·mysql·微信小程序·毕业设计
张np5 小时前
java基础-Deque 接口
java·开发语言
骚戴5 小时前
大语言模型(LLM)进阶:从闭源大模型 API 到开源大模型本地部署,四种接入路径全解析
java·人工智能·python·语言模型·自然语言处理·llm·开源大模型
东华万里5 小时前
Release 版本禁用 assert:NDEBUG 的底层逻辑与效率优化
java·jvm·算法
silence2506 小时前
基于 (java) validation-api、hibernate-validator 的数据校验扩展
java
Alsn866 小时前
24.idea专业版安装+maven、tomcat安装并部署到idea
java·ide·intellij-idea
胡闹546 小时前
海康和大华厂商的RTSP取流地址格式进行拉流直播
java·网络
手揽回忆怎么睡6 小时前
Java集成whisper.cpp
java·开发语言·whisper
无名-CODING6 小时前
栈与队列学习笔记
java·笔记
Hui Baby6 小时前
LSM 原理、实现及与 B+ 树的核心区别
java·linux·算法