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"));
    }
}
相关推荐
利刃大大1 分钟前
【c++中间件】redis介绍 && redis-plus-plus库使用
c++·redis·中间件
q***81643 分钟前
【Redis】centos7 systemctl 启动 Redis 失败
数据库·redis·缓存
程序员小假9 分钟前
有了解过 SpringBoot 的参数配置吗?
java·后端
f***24119 分钟前
java学习进阶之路,如果从一个菜鸟进阶成大神
java·开发语言·学习
ALex_zry13 分钟前
高并发系统渐进式改造技术调研报告:策略、架构与实战
java·运维·架构
88号技师14 分钟前
2025年9月一区SCI-孤行尺蠖觅食优化算法Solitary Inchworm Foraging-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
Yue丶越14 分钟前
【Python】基础语法入门(四)
linux·开发语言·python
SimonKing23 分钟前
等保那些事
java·后端·程序员
带土123 分钟前
5. QT之Q_OBJECT详解
开发语言·qt
数据牧羊人的成长笔记26 分钟前
Hadoop 分布式计算MapReduce和资源管理Yarn 2
开发语言·php