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"));
    }
}
相关推荐
李慕婉学姐2 小时前
【开题答辩过程】以《基于Android的出租车运行监测系统设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
java·后端·vue
小鸡吃米…2 小时前
Python 列表
开发语言·python
m0_740043732 小时前
SpringBoot05-配置文件-热加载/日志框架slf4j/接口文档工具Swagger/Knife4j
java·spring boot·后端·log4j
编织幻境的妖2 小时前
SQL查询连续登录用户方法详解
java·数据库·sql
kaikaile19953 小时前
基于C#实现一维码和二维码打印程序
开发语言·c#
我不是程序猿儿3 小时前
【C#】画图控件的FormsPlot中的Refresh功能调用消耗时间不一致缘由
开发语言·c#
未若君雅裁3 小时前
JVM面试篇总结
java·jvm·面试
rit84324993 小时前
C# Socket 聊天室(含文件传输)
服务器·开发语言·c#
kk哥88993 小时前
C++ 对象 核心介绍
java·jvm·c++
嘉琪0013 小时前
Vue3+JS 高级前端面试题
开发语言·前端·javascript