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"));
    }
}
相关推荐
CodeCraft Studio3 小时前
国产化Excel处理控件Spire.XLS教程:如何使用 Java 将 TXT 文本转换为 Excel 表格
java·word·excel·spire·文档格式转换·txt转excel
Predestination王瀞潞3 小时前
Python3:Eighth 函数
开发语言·python
朝新_3 小时前
【SpringBoot】玩转 Spring Boot 日志:级别划分、持久化、格式配置及 Lombok 简化使用
java·spring boot·笔记·后端·spring·javaee
m0_748248023 小时前
Spring设计模式刨根问底
java·spring·设计模式
喝杯牛奶丶3 小时前
MySQL隔离级别:大厂为何偏爱RC?
java·数据库·mysql·面试
一 乐3 小时前
二手车销售|汽车销售|基于SprinBoot+vue的二手车交易系统(源码+数据库+文档)
java·前端·数据库·vue.js·后端·汽车
夜晚中的人海3 小时前
【C++】分治-快速排序算法习题
开发语言·c++·排序算法
爱编程的鱼4 小时前
想学编程作为今后的工作技能,学哪种语言适用性更强?
开发语言·算法·c#·bug
yugi9878384 小时前
基于MATLAB的心电信号去噪
开发语言·matlab