SpringDataRedis

快速入门

SpringBoot已经提供了对SpringDataRedis的支持,使用非常简单:

1.引入依赖

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

<!--连接池依赖-->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

2.配置文件

XML 复制代码
spring:
  data:
    redis:
      host: 192.168.100.128
      port: 6379
      password: 1234
      database: 0
      lettuce:
        pool:
          max-active: 8      # 最大连接数
          max-idle: 8        # 最大空闲连接
          min-idle: 0        # 最小空闲连接
          max-wait: 100ms    # 获取连接等待时间

host 和 password 需要改成自己的

database默认为0,即1号库

3.注入RedisTemplate

java 复制代码
@Autowired
private RedisTemplate redisTemplate;

4.编写测试

java 复制代码
@SpringBootTest
public class RedisTest {
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void testString() {
        // 插入一条string类型数据
        redisTemplate.opsForValue().set("name", "李四");
        // 读取一条string类型数据
        Object name = redisTemplate.opsForValue().get("name");
        System.out.println("name = " + name);
    }
}

序列化

在执行完测试之后,得到如下结果

这并不是我们想要的,因为这里使用的是默认的序列化方式

接下来需要解决这个问题

方案一

自定义RedisTemplate的序列化方式,代码如下(可复用):

java 复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisConfig {

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

}

如果出现问题,可能是没有引入依赖(平时不需要引入,因为Spring Boot 整合的 Spring MVC会自动导入):

XML 复制代码
<!--Jackson依赖-->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
</dependency>

这个时候测试结果为:

这才是我们想要的结果

但是这种方式在存储value为对象的时候,会把字节码也存进去,占用多余的空间

方案二(推荐)

使用SpringRedisTemplate

不需要额外的配置文件,测试代码如下:

java 复制代码
import com.example.redis.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;

@SpringBootTest
public class RedisStringTest {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final ObjectMapper mapper = new ObjectMapper();

    @Test
    void testSaveUser() throws JsonProcessingException {

        // 创建User对象
        User user = new User("张三", 18);
        // 手动序列化
        String json = mapper.writeValueAsString(user);
        // 插入一条string类型数据
        stringRedisTemplate.opsForValue().set("user:200", json);
        // 读取一条string类型数据
        String jsonUser = stringRedisTemplate.opsForValue().get("user:200");
        // 手动反序列化
        User user1 = mapper.readValue(jsonUser, User.class);
        System.out.println("user1 = " + user1);
    }

}

这种方法需要手动的去序列化和反序列化对象,如果是字符串就不用了

相关推荐
HalvmånEver41 分钟前
7.高并发内存池大页内存申请释放以及使用定长内存池脱离new
java·spring boot·spring
凤山老林1 小时前
SpringBoot 使用 H2 文本数据库构建轻量级应用
java·数据库·spring boot·后端
赶路人儿2 小时前
UTC时间和时间戳介绍
java·开发语言
dreamread2 小时前
【SpringBoot整合系列】SpringBoot3.x整合Swagger
java·spring boot·后端
6+h2 小时前
【java】基本数据类型与包装类:拆箱装箱机制
java·开发语言·python
把你毕设抢过来2 小时前
基于Spring Boot的社区智慧养老监护管理平台(源码+文档)
数据库·spring boot·后端
一直都在5722 小时前
Spring面经
java·后端·spring
xiaoye37082 小时前
如何在Spring中使用注解配置Bean的生命周期回调方法?
java·spring
闻哥2 小时前
深入Redis的RDB和AOF两种持久化方式以及AOF重写机制的分析
java·数据库·spring boot·redis·spring·缓存·面试
jgyzl3 小时前
2026.3.12 常见的缓存读写策略
java·后端·spring