Redis - Spring Data Redis 操作 Jedis 、Lettuce 、 Redisson

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: Redis - Spring Data Redis 操作 Jedis 、Lettuce 、 Redisson

20210216205048153.png

官网

https://spring.io/projects/spring-data-redis


20210216205015533.png


我们知道常用的Redis客户端 https://redis.io/clients#java



2021021620055425.png



怎么还有 Spring Data Redis ?


莫慌,小兄弟, 来看个关系图 帮你捋一捋



20210216194405463.png


Jedis VS Lettuce


在 spring-boot-starter-data-redis 项目 2.X 版本中 ,默认使用 Lettuce 作为 Java Redis 工具库 , 为啥不用jedis 了?


Why is Lettuce the default Redis client used in Spring Session Redis? #789


20210216203740279.png


也有可能跟jedis 有一段时间不更新了有关系~


Jedis Code

POM依赖

  <dependencies>
        <!-- 实现对 Spring Data Redis 的自动化配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <!-- 去掉  Lettuce 的依赖,  Spring Boot 优先使用 Lettuce 作为 Redis 客户端 -->
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--  Jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
        <!-- 单元测试 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 使用 fastjson 作为 JSON 序列化的工具 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.61</version>
        </dependency>
        <!-- Spring Data Redis 默认使用 Jackson 作为 JSON 序列化的工具 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
    </dependencies>


配置文件

spring:
  # 对应 RedisProperties 类
  redis:
    host: 127.0.0.1
    port: 6379
    password: # Redis 服务器密码,默认为空。生产中,一定要设置 Redis 密码!
    database: 0 # Redis 数据库号,默认为 0 。
    timeout: 0 # Redis 连接超时时间,单位:毫秒。
    # 对应 RedisProperties.Jedis 内部类
    jedis:
      pool:
        max-active: 8 # 连接池最大连接数,默认为 8 。使用负数表示没有限制。
        max-idle: 8 # 默认连接数最小空闲的连接数,默认为 8 。使用负数表示没有限制。
        min-idle: 0 # 默认连接池最小空闲的连接数,默认为 0 。允许设置 0 和 正数。
        max-wait: -1 # 连接池最大阻塞等待时间,单位:毫秒。默认为 -1 ,表示不限制。


配置类

package com.artisan.config;
import org.springframework.beans.factory.annotation.Autowired;
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.RedisSerializer;
/**
 * @author 小工匠
 * @version 1.0
 * @description: TODO
 * @date 2021/2/16 21:07
 * @mark: show me the code , change the world
 */
@Configuration
public class RedisConfiguration {
    @Autowired
    private RedisConnectionFactory connectionFactory;
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String,Object> template = new RedisTemplate();
          template.setConnectionFactory(connectionFactory);
          // 序列化工具
          Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
          ObjectMapper om = new ObjectMapper();
          om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
          om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
          jackson2JsonRedisSerializer.setObjectMapper(om);
          StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
          template.setKeySerializer(stringRedisSerializer);
          template.setValueSerializer(jackson2JsonRedisSerializer);
          template.setHashKeySerializer(jackson2JsonRedisSerializer);
          template.setHashValueSerializer(jackson2JsonRedisSerializer);
          template.afterPropertiesSet();
        return template;
    }
}


单元测试

 package com.artisan;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
/**
 * @author 小工匠
 * @version 1.0
 * @description: TODO
 * @date 2021/2/16 20:56
 * @mark: show me the code , change the world
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class JedisTest {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Test
    public void testStringSetKey() {
        // set
        stringRedisTemplate.opsForValue().set("artisan", "good1");
        // get
        String artisan = stringRedisTemplate.opsForValue().get("artisan");
        System.out.println(artisan);
    }
}



20210216213842127.png

Lettuce Code


2.x 以上默认 使用的客户端为Lettuce , 参考 Spring Session - 使用Spring Session从零到一构建分布式session

这里就不赘述了。


Redisson Code

POM依赖

  <dependencies>
        <!--  Redisson  -->
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson-spring-boot-starter</artifactId>
            <version>3.11.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.61</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
    </dependencies>



配置文件

20210216232600518.png


【application.yml】

spring:
  # 对应 RedisProperties 类
  redis:
    host: 127.0.0.1
    port: 6379
#    password: # Redis 服务器密码,默认为空。生产中,一定要设置 Redis 密码!
    database: 0 # Redis 数据库号,默认为 0 。
    timeout: 0 # Redis 连接超时时间,单位:毫秒。
    # 对应 RedissonProperties 类  如果为空 需要注释掉
#    redisson:
#      config: classpath:redisson.yml # 具体的每个配置项,见 org.redisson.config.Config 类。


使用 Spring Boot 整合 Redisson 时候,通过该配置项,引入一个外部的 Redisson 相关的配置文件 ,引入了 classpath:redisson.yaml 配置文件


引入的 redisson.config 对应的配置文件,对应的类是 org.redisson.config.Config 类。因为示例中,我们使用的比较简单,所以就没有做任何 Redisson 相关的自定义配置。 如果没有配置任何内容,需要在 application.yml 里注释掉 redisson.config 。


具体配置信息可参考 Spring Boot2.x 整合lettuce redis 和 redisson


配置类

同上

package com.artisan.config;
import org.springframework.beans.factory.annotation.Autowired;
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.RedisSerializer;
/**
 * @author 小工匠
 * @version 1.0
 * @description: TODO
 * @date 2021/2/16 21:07
 * @mark: show me the code , change the world
 */
@Configuration
public class RedisConfiguration {
    @Autowired
    private RedisConnectionFactory connectionFactory;
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String,Object> template = new RedisTemplate();
          template.setConnectionFactory(connectionFactory);
          // 序列化工具
          Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
          ObjectMapper om = new ObjectMapper();
          om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
          om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
          jackson2JsonRedisSerializer.setObjectMapper(om);
          StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
          template.setKeySerializer(stringRedisSerializer);
          template.setValueSerializer(jackson2JsonRedisSerializer);
          template.setHashKeySerializer(jackson2JsonRedisSerializer);
          template.setHashValueSerializer(jackson2JsonRedisSerializer);
          template.afterPropertiesSet();
        return template;
    }
}


单元测试

@Test
    public void test() {
        stringRedisTemplate.opsForValue().set("uuu", "xxxxx");
    }


20210216232925384.png


相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
1月前
|
NoSQL 安全 Java
Spring Boot3整合Redis
Spring Boot3整合Redis
63 1
|
1月前
|
存储 缓存 Java
【Spring原理高级进阶】有Redis为啥不用?深入剖析 Spring Cache:缓存的工作原理、缓存注解的使用方法与最佳实践
【Spring原理高级进阶】有Redis为啥不用?深入剖析 Spring Cache:缓存的工作原理、缓存注解的使用方法与最佳实践
|
1月前
|
JSON NoSQL Java
【Redis】2、Redis 的 Java 客户端(Jedis 和 SpringDataRedis)
【Redis】2、Redis 的 Java 客户端(Jedis 和 SpringDataRedis)
45 0
|
2月前
|
消息中间件 NoSQL Java
Redis Streams在Spring Boot中的应用:构建可靠的消息队列解决方案【redis实战 二】
Redis Streams在Spring Boot中的应用:构建可靠的消息队列解决方案【redis实战 二】
246 1
|
1月前
|
NoSQL Java Redis
【Redis深度专题】「踩坑技术提升」一文教会你如何在支持Redis在低版本Jedis情况下兼容Redis的ACL机制
【Redis深度专题】「踩坑技术提升」一文教会你如何在支持Redis在低版本Jedis情况下兼容Redis的ACL机制
254 0
|
1月前
|
缓存 NoSQL Java
spring cache整合redis实现springboot项目中的缓存功能
spring cache整合redis实现springboot项目中的缓存功能
46 1
|
1月前
|
存储 NoSQL Java
[Redis]——Spring整合Redis(SpringDataRedis)
[Redis]——Spring整合Redis(SpringDataRedis)
|
1月前
|
Java 数据库 Spring
如何使用Spring Data JPA完成审计功能
如何使用Spring Data JPA完成审计功能
|
1月前
|
监控 NoSQL Java
Spring Boot集成Redis启动失败【Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool2.impl.G】
Spring Boot集成Redis启动失败【Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool2.impl.G】
|
1月前
|
NoSQL Java 定位技术