SpringDataRedis

目录

一、Jedis连接池

  • Jedis连接本身线程不安全
  • 频繁的创建和销毁连接会有性能损耗
java 复制代码
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisConnectionFactory {
    private static final JedisPool jedisPool;

    // 静态代码块实例化 JedisPool
    static {
        // 配置连接池
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        // 允许创建的最大连接数
        poolConfig.setMaxTotal(8);
        // 最大空闲连接(即便没有人访问连接池,连接池预备的最大连接数)
        poolConfig.setMaxIdle(8);
        // 最小空闲连接(即便没有人访问连接池,连接池预备的最小连接数)
        poolConfig.setMinIdle(0);
        // 等待时长(当连接池中没有连接可用时等待的时长s,超时会报错,默认-1无限等待)
        poolConfig.setMaxWaitMillis(1000);
        // 创建连接池对象
       jedisPool = new JedisPool(poolConfig, "192.168.50.128", 6379);
    }

    // 调用该方法会从jedis连接池中获得一个jedis对象
    public static Jedis getJedis(){
        return jedisPool.getResource();
    }
}

二、SpringDataRedis

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

  • 整合了Lettuce和Jedis,更安全且方便的操作Redis
  • 提供了RedisTemplate统一API来操作Redis
  • 支持Redis的发布订阅模型
  • 支持Redis哨兵和Redis集群
  • 支持基于Lettuce的响应式编程
  • 支持基于JDK、JSON、字符串、Spring对象的数据序列化以及反序列化
  • 支持基于Redis的JDKCollection实现

1.引入SpringDataRedis:

  • 引入依赖:
xml 复制代码
        <!--SpringDataRedis依赖-->
        <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>
  • 配置redis:
yml 复制代码
spring:
  data:
    redis:
      host: 192.168.50.128
      port: 6379
      lettuce:
        pool:
          max-active: 8
          max-idle: 8
          min-idle: 0
          max-wait: 100

2.RedisTemplate:

SpringDataRedis中提供了RedisTemplate工具类,将每个Redis数据类型的所有方法各封装成一个对象,使用该对象的方法对特定的Redis数据类型进行操作

java 复制代码
package com.example.redisdemo;

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.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

@SpringBootTest
class RedisDemoApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {
        // ValueOperations 对象用来操作String类型
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("myid","myvalue");

        System.out.println(valueOperations.get("myid"));
    }

}

三、SpringDataRedis序列化

RedisTemplate可以接收任意Object类型 作为值写入Redis,只不过写入前会把Object序列化为字节形式 ,默认采用JDK序列化 ,得到如下结果:

如果想要将存入的key和value都以更加直观的方式展示,就需要使用序列化将java中的变量序列化后存储到redis中。

1.自定义RedisTemplate实现自动序列化:

自定义RedisTemplate的序列化的原理是:

  • 存的过程中:
    • 对于KEY使用RedisSerializer.string()方式将Object转换成String后再存到redis中
    • 对VALUE采用jsonRedisSerializer()方式,如果是字符串那么将Object转换成String后再存到redis中。如果是Bean对象,那么会将内容转换成JSON格式并添加类路径存到redis中。
  • 取的过程中:
    • 对于KEY直接取字符串即可
    • 是对于VALUE:如果是字符串那么直接取字符串,返回String。如果是json格式,那么会根据类路径将json的内容映射到Bean的属性中,并返回对应的对象类型。
java 复制代码
package com.example.redisdemo.util;

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 connectionfactory){
        // 创建RedisTemplate对象
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        // 设置连接工厂
        template.setConnectionFactory(connectionfactory);
        // 创建JSON序列化工具
        GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        //设置KEY的序列化,RedisSerializer.string()底层是getBytes()
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        //设置VALUE的序列化
        template.setValueSerializer(jsonRedisSerializer);
        template.setHashValueSerializer(jsonRedisSerializer);

        return template;
    }
}
  • 测试代码:
java 复制代码
package com.example.redisdemo;

import com.example.redisdemo.bean.User;
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.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

@SpringBootTest
class RedisDemoApplicationTests {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Test
    void testA() {
        // ValueOperations 对象用来操作String类型
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("myid","myvalue");

        System.out.println(valueOperations.get("myid"));
    }
    @Test
    void testB() {
        User user = new User("haha", 15);

        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("haha", user);

        System.out.println(valueOperations.get("haha"));
    }

}

2.使用StringRedisTemplate实现序列化:

方法1将key和value都实现了序列化和反序列化,但是存在一个问题,当value存入的是bean对象时,序列化过程会将bean的类路径同时存入redis(jsonRedisSerializer导致的),目的是为了在读时实现反序列化转成bean,但存入额外的类路径非常占用存储空间:

StringRedisTemplate是Spring提供的类,其中key和value的序列化方式默认是String,而不是jsonRedisSerializer,这种方式在存储时不会额外的存入对象的类路径,但是StringRedisTemplate对于输入要求key和value必须是string类型,所以需要在存时手动编写序列化过程将java对象转换成string,取时将手动编写反序列化过程将string转换成java对象

java 复制代码
package com.example.redisdemo;


import com.example.redisdemo.bean.User;
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;
import org.springframework.data.redis.core.ValueOperations;

@SpringBootTest
class RedisDemoApplicationTest2 {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    // SpringMVC中默认使用的JSON处理工具
    private static final ObjectMapper mapper = new ObjectMapper();

    @Test
    void testB() throws Exception{
        User user = new User("haha", 15);
        // ValueOperations 对象用来操作String类型
        ValueOperations valueOperations = stringRedisTemplate.opsForValue();

        //1.读时手动序列化
        String json = mapper.writeValueAsString(user);
        valueOperations.set("haha", json);

        String json_user = (String) valueOperations.get("haha");
        //2.取时手动反序列化
        User user1 = mapper.readValue(json_user, User.class);
        System.out.println(user1);
    }

    @Test
    void testA() {
        // ValueOperations 对象用来操作String类型
        ValueOperations valueOperations = stringRedisTemplate.opsForValue();
        valueOperations.set("myid","myvalue");

        System.out.println(valueOperations.get("myid"));
    }
}
相关推荐
huwei853几秒前
Q打印表格内容类
开发语言·qt
一嘴一个橘子2 分钟前
spring-aop 的 基础使用 -3 - 切点表达式 的提取、复用
java
Re_zero4 分钟前
Java新手避坑:为什么我劝你放弃 scanner.nextInt()?
java
oioihoii10 分钟前
构建高并发AI服务网关:C++与gRPC的工程实践
开发语言·c++·人工智能
X***078825 分钟前
从底层逻辑到工程实践,深入理解C语言在计算机世界中的核心地位与持久价值
c语言·开发语言
晚枫歌F30 分钟前
io_uring的介绍和实现
开发语言·php
Good_Starry38 分钟前
Java——反射
java
时光追逐者41 分钟前
TIOBE 公布 C# 是 2025 年度编程语言
开发语言·c#·.net·.net core·tiobe
花归去44 分钟前
echarts 柱状图曲线图
开发语言·前端·javascript
又是忙碌的一天1 小时前
SpringBoot 创建及登录、拦截器
java·spring boot·后端