springboot 整合 redis (RedisConnection RedisConnectionFactory Redis Template redis序列化)

目录

1.起步

2.钻进去康一康

2.1.RedisConnection

2.2.RedisConnectionFactory

2.3. RedisTemplate

2.4.数据的序列化


1.起步

还是老规矩,直接开始,先用最简单的配置运行起来:

pom.xml依赖 (只列出重要依赖)


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

applicaiton.yml 配置:

spring:
  # redis 配置
  redis:
    database: 8
    # 地址
    host: 127.0.0.1
    # 端口,默认为6379
    port: 6379
    # 密码
    password:
    # 连接超时时间
    timeout: 10s
    lettuce:
      pool:
        # 连接池中的最小空闲连接
        min-idle: 0
        # 连接池中的最大空闲连接
        max-idle: 8
        # 连接池的最大数据库连接数
        max-active: 8
        # #连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1ms

写一个简单的工具类:RedisUtils

    public class RedisUtils {
    /**
     * 此处使用的是Spring 默认提供的redisTemplate,(使用 JackSon 做序列化)
     */
    @Resource
    public RedisTemplate redisTemplate;

     /**
     * 插入缓存对象,Integer、String、实体类等
     *
     * @param key      缓存的键值
     * @param value    缓存的值
     * @param timeout  时间
     * @param timeUnit 时间颗粒度
     * @return 缓存的对象
     */
    public <T> ValueOperations<String, T> setCacheObject(String key, T value, Integer timeout, TimeUnit timeUnit) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        operation.set(key, value, timeout, timeUnit);
        return operation;
    }  

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(String key) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        T t = operation.get(key);
        return t;
    }

}

简单测试一下:(这里要记得先在命令行使用命令 redis-server 启动 redis 服务)

    @Test
    public void test1() {
        redisUtils.setCacheObject("username", "swing");
        System.out.println((String) redisUtils.getCacheObject("username"));
    }

//结果:swing

2.钻进去康一康

简单的例子可以运行了,现在我们来简要分析一下原理

redis和MySQL一样,都是数据库,只不过redis是非关系型的,而MySQL是关系型的,但他们还是有很多共同点的,

java 使用 JDBC 连接数据库,JDBC提供了一套标准的接口(例如Connection,Statement等),而这套接口的实现由各大数据库的厂家提供(也就是平时所说的数据库连接驱动)

同样,sprign-redis 也为 redis 提供了一些这样的接口,这里重点说一下 RedisConnection and RedisConnectionFactory 

2.1.RedisConnection

RedisConnection提供了Redis通信的核心构建块, 和JDBC中的Connection类似

RedisConnection 需要使用 RedisConnectionFactory获取

2.2.RedisConnectionFactory

RedisConnectionFactory 常用的有两种连接器的实现: Lettuce Connector 和 Jedis Connector,两种实现方式的配置也很简单,如下:

  • Lettuce (spring-boot-redis的默认RedisConnectionFactory的默认实现)
  <dependency>
    <groupId>io.lettuce</groupId>
    <artifactId>lettuce-core</artifactId>
    <version>5.3.1.RELEASE</version>
  </dependency>
  @Bean
  public LettuceConnectionFactory redisConnectionFactory() {
    return new LettuceConnectionFactory(new RedisStandaloneConfiguration("server", 6379));
  }
  • Jedis
  <dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.3.0</version>
  </dependency>
  @Bean
  public JedisConnectionFactory redisConnectionFactory() {
    RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("server", 6379);
    return new JedisConnectionFactory(config);
  }

2.3. RedisTemplate

RedisConnection提供了接受和返回二进制值(字节数组)的低级方法,我们直接去使用RedisConnection操作redis的话无意效率太低(使用原生JDBC便能体会到这一点)所以便有了RedisTemplate , 它负责序列化和连接管理,使用户无需处理此类细节。 使操作redis 更简单高效

2.4.数据的序列化

Redis中存储的数据仅为字节。虽然Redis本身支持各种类型,但在大多数情况下,它们是指数据的存储方式,而不是其表示的内容。由用户决定是否将信息转换为字符串或任何其他对象。 在Spring Data中,用户(自定义)类型和原始数据之间的转换(反之亦然)由org.springframework.data.redis.serializer包中序列化器处理。

spring内置了这几种序列化器:(所有的序列化器都是 RedisSerializer 的实现)

redis支持对键和值提供不同的序列化方式,如下实例:

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        //指定键的序列化器
        template.setKeySerializer(new StringRedisSerializer());
        //指定值的序列化器
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();

        return template;
    }

同样,也支持自定义序列化器,例如使用FastJson 等

猜你喜欢

转载自blog.csdn.net/qq_42013035/article/details/106836163
今日推荐