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);
    }

}

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

相关推荐
爬山算法31 分钟前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
kfyty72542 分钟前
集成 spring-ai 2.x 实践中遇到的一些问题及解决方案
java·人工智能·spring-ai
猫头虎44 分钟前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
李少兄44 分钟前
在 IntelliJ IDEA 中修改 Git 远程仓库地址
java·git·intellij-idea
忆~遂愿1 小时前
ops-cv 算子库深度解析:面向视觉任务的硬件优化与数据布局(NCHW/NHWC)策略
java·大数据·linux·人工智能
小韩学长yyds1 小时前
Java序列化避坑指南:明确这4种场景,再也不盲目实现Serializable
java·序列化
仟濹1 小时前
【Java基础】多态 | 打卡day2
java·开发语言
Re.不晚1 小时前
JAVA进阶之路——无奖问答挑战2
java·开发语言
Ro Jace2 小时前
计算机专业基础教材
java·开发语言
mango_mangojuice2 小时前
Linux学习笔记(make/Makefile)1.23
java·linux·前端·笔记·学习