Advertisement

【项目实战】你知道项目中到底应该用 Lettuce 还是 Jedis 吗?

阅读量:

👉博主介绍:博主专注于应用安全与大数据领域,在开发实践中积累了丰富的经验。他/她拥有多年的面试辅导经验以及在Java领域的深厚理论与实践经验。作为一位在Web技术架构设计方面拥有丰富实践经验的技术专家,并具备阿里云认证、华为云认证与优化能力的资深人士。此外,在51CTO平台也担任过认证技术专家角色

⛪️ 个人社区:个人社区
💞 个人主页:个人主页
🙉 专栏地址: ✅ Java 中级
🙉八股文专题:剑指大厂,手撕 Java 八股文

在这里插入图片描述

文章目录

      • 1. Lettuce 和 Jedis 有什么区别?
        • 1.1 架构设计
    • 1.2 性能

    • 1.3 功能支持

    • 1.4 生态系统

      • 2. 项目中到底应该用哪种?
        • 2.1 选择 Jedis 的场景
    • 2.2 选择 Lettuce 的场景

      • 3. Jedis 如何使用?
        • 3.1 添加依赖
    • 3.2 连接 Redis

      • 4. Lettuce 如何使用?
        • 4.1 添加依赖
    • 4.2 连接 Redis

  • 5、我们项目均集成于Spring框架中,在此背景下实现两种框架之间的切换。

    • [5.1] 配置必要的配置项
      • 激活Lettuce组件作为数据库驱动

      • [5.2] 完成Redis数据模板的配置设置

        • [5.2.1] 采用Jedis库进行连接建立机制
          • [5.2.2] 实现对事务管理功能的精细控制通过Lettuce组件完成
      • 5.3 使用 RedisTemplate

      • 5.4 切换客户端

      • 5.5 配置文件

      • application.properties

1. Lettuce 和 Jedis 有什么区别?

Lettuce 和 Jedis 是两个广泛使用的 Redis Java 客户端库。每个都有其独特的优势和应用场景。下面我们将重点分析它们的主要区别。

1.1 架构设计

Jedis

  • blocking-style : Jedis is a synchronous and blocking client that interacts with the Redis server.
    Each operation waits for the server's response before proceeding to the next task.
  • connection pool : To optimize performance, Jedis utilizes a connection pool for managing interactions with the Redis server.
    Each operation acquires a connection from the pool and releases it after completion.

Lettuce

  • Non-blocking: Lettuce is an asynchronous, non-blocking client-side application built upon the Netty framework. It efficiently manages multiple concurrent requests without the overhead of creating new threads for each request.
  • Connection pooling: Lettuce employs a single connection to handle multiple commands, effectively reducing connection overhead and enhancing performance.
1.2 性能

Jedis

  • 基于阻塞机制实现的应用可能在高并发场景下表现出较差性能,在网络延迟较大时尤为明显。
  • 连接池的管理及维护会产生一定的额外负担。

Lettuce

  • 无阻塞模式下的系统架构在处理高并发任务时展现出色性能,在多线程环境下能够更高效地分配CPU资源并充分利用网络带宽。
  • 单点连接复用来减少网络通信开销的方式能够显著提升网络传输效率。
1.3 功能支持

Jedis

  • Redis 的主要功能包括:键-值对存储与读取;事务操作涉及;发布订阅涉及。
  • 拥有活跃的社区支持者,并提供丰富的文档和示例说明。

Lettuce

  • 也支持 Redis 的大部分功能,并且包括集群和哨兵等高级特性。
  • 该特性使其更适合处理复杂的高性能场景。
1.4 生态系统

Jedis

Jedis 因为其悠久的历史,在众多项目中得到了广泛应用,并拥有丰富的第三方库和支持框架。

Lettuce

*新兴技术虽还处于发展中期阶段但展现出强劲的发展势头如今已成为越来越多项目的主流选择尤其是像Spring Data Redis这样的现代框架中Lettuce已经逐渐占据重要地位

2. 项目中到底应该用哪种?

根据不同的项目需求和具体应用场景而定

2.1 选择 Jedis 的场景
  • 简单应用 :如果你的应用相对简单且对性能要求不高,则 Jedis 是一个值得考虑的替代方案。
    • 现有项目迁移 :如果你已经在使用 Jedis 并未遇到明显的性能瓶颈,则建议继续使用 Jedis 以避免不必要的迁移成本。
    • 社区支持 :Jedis 提供了强大的技术支持网络以及众多的技术支持资源。
2.2 选择 Lettuce 的场景

高负载处理场景:如果您的系统或应用程序需要应对大量并行请求,在使用Lettuce时会发现其无阻塞架构能够有效优化性能指标。

高级功能模块 :Lettuce 具备多种高级特性功能(包括灵活配置的 Redis 集群和哨兵等扩展特性),特别适用于对复杂系统需求较高的场景。

如果你的项目基于Spring Data Redis等现代框架,则Lettuce是一个值得考虑的选择;其优势在于集成能力更强。

Jedis :适合简单应用和现有项目的维护,社区支持丰富。

Lettuce :适合高并发、高性能和复杂操作的场景,现代框架集成更好。

基于你特殊的开发场景和功能需求,在性能方面寻求突破的前提下

3. Jedis 如何使用?

Jedis 是一个广泛应用的 Redis Java 客户端软件包, 提供了简便的操作方式供开发者与 Redis 服务器实现交互功能。下面提供了一个基本示例, 包括客户端连接建立、执行数据库操作以及完成连接关闭等步骤说明

3.1 添加依赖

建议为你的项目引入Jedis库;如果使用Maven,则应在pom.xml文件里指定相应的依赖项

复制代码
    <dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>4.0.1</version>
    </dependency>
    
    
      
      
      
      
      
    
    AI写代码
3.2 连接 Redis

你可以直接连接到 Redis 服务器,或者使用连接池来管理连接。

直接连接

复制代码
    import redis.clients.jedis.Jedis;
    
    public class JedisExample {
    public static void main(String[] args) {
        // 连接到本地的 Redis 服务
        Jedis jedis = new Jedis("localhost", 6379);
    
        try {
            // 设置键值对
            jedis.set("key1", "value1");
    
            // 获取键值
            String value = jedis.get("key1");
            System.out.println("Value of key1: " + value);
    
            // 删除键
            jedis.del("key1");
            System.out.println("Key1 deleted");
    
        } finally {
            // 关闭连接
            jedis.close();
        }
    }
    }
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    AI写代码

使用连接池

复制代码
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    import redis.clients.jedis.JedisPoolConfig;
    
    public class JedisPoolExample {
    public static void main(String[] args) {
        // 配置连接池
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(128); // 最大连接数
        poolConfig.setMaxIdle(100);  // 最大空闲连接数
        poolConfig.setMinIdle(10);   // 最小空闲连接数
    
        // 创建连接池
        JedisPool jedisPool = new JedisPool(poolConfig, "localhost", 6379);
    
        try (Jedis jedis = jedisPool.getResource()) {
            // 设置键值对
            jedis.set("key1", "value1");
    
            // 获取键值
            String value = jedis.get("key1");
            System.out.println("Value of key1: " + value);
    
            // 删除键
            jedis.del("key1");
            System.out.println("Key1 deleted");
    
        } finally {
            // 关闭连接池
            jedisPool.close();
        }
    }
    }
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    AI写代码

4. Lettuce 如何使用?

Lettuce is a non-blocking Redis Java client built upon the Netty framework, offering high-performance Redis access. Below is a fundamental usage example, encompassing connection, operations, and connection closure processes.

4.1 添加依赖

第一步,在你的项目中引入Lettuce依赖项。如果采用Maven框架,则应在项目的pom.xml文件中,请配置以下Lettuce依赖项:

复制代码
    <dependency>
    <groupId>io.lettuce.core</groupId>
    <artifactId>lettuce-core</artifactId>
    <version>6.1.6.RELEASE</version>
    </dependency>
    
    
      
      
      
      
      
    
    AI写代码
4.2 连接 Redis

你可以直接连接到 Redis 服务器,或者使用连接池来管理连接。

直接连接

复制代码
    import io.lettuce.core.RedisClient;
    import io.lettuce.core.api.StatefulRedisConnection;
    import io.lettuce.core.api.sync.RedisCommands;
    
    public class LettuceExample {
    public static void main(String[] args) {
        // 创建 Redis 客户端
        RedisClient redisClient = RedisClient.create("redis://localhost:6379");
    
        // 获取连接
        try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
            // 获取同步命令接口
            RedisCommands<String, String> syncCommands = connection.sync();
    
            // 设置键值对
            syncCommands.set("key1", "value1");
    
            // 获取键值
            String value = syncCommands.get("key1");
            System.out.println("Value of key1: " + value);
    
            // 删除键
            syncCommands.del("key1");
            System.out.println("Key1 deleted");
    
        } finally {
            // 关闭客户端
            redisClient.shutdown();
        }
    }
    }
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    AI写代码

使用连接池

复制代码
    import io.lettuce.core.RedisClient;
    import io.lettuce.core.RedisURI;
    import io.lettuce.core.resource.ClientResources;
    import io.lettuce.core.resource.DefaultClientResources;
    import io.lettuce.core.api.StatefulRedisConnection;
    import io.lettuce.core.api.sync.RedisCommands;
    import com.lambdaworks.redis.resource.ClientResourcesBuilder;
    
    public class LettucePoolExample {
    public static void main(String[] args) {
        // 创建客户端资源
        ClientResources clientResources = DefaultClientResources.builder().build();
    
        // 创建 Redis 客户端
        RedisClient redisClient = RedisClient.create(clientResources, RedisURI.create("redis://localhost:6379"));
    
        // 获取连接
        try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {
            // 获取同步命令接口
            RedisCommands<String, String> syncCommands = connection.sync();
    
            // 设置键值对
            syncCommands.set("key1", "value1");
    
            // 获取键值
            String value = syncCommands.get("key1");
            System.out.println("Value of key1: " + value);
    
            // 删除键
            syncCommands.del("key1");
            System.out.println("Key1 deleted");
    
        } finally {
            // 关闭客户端
            redisClient.shutdown();
            clientResources.shutdown();
        }
    }
    }
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    AI写代码

我们的项目均集成至Spring框架中,在Spring内如何实现两种框架的切换使用

在实际项目开发中,在Spring框架中整合Redis客户端是一种普遍采用的做法。(如Jedis和Lettuce等客户端工具)Spring Data Redis通过提供统一的操作接口简化了不同Redis客户端之间的切换过程使其变得更加简便

5.1 添加依赖

为你的项目配置所需的Redis组件,在其管理架构下集成了一个强大的数据持久化服务框架。如果你使用Maven工具,则可以在项目的构建阶段通过管理插件轻松地完成这一配置过程;具体来说,在pom.xml文件中你可以按照如下方式配置所需的Redis组件:

Jedis 依赖

复制代码
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    </dependency>
    
    
      
      
      
      
      
      
      
      
    
    AI写代码
Lettuce 依赖
复制代码
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
    <groupId>io.lettuce.core</groupId>
    <artifactId>lettuce-core</artifactId>
    </dependency>
    
    
      
      
      
      
      
      
      
      
    
    AI写代码
5.2 配置 RedisTemplate

Spring Data Redis 支持了 RedisTemplate 功能,并将其定义为一个功能强大的模板类工具。根据需要可以对 RedisConnectionFactory 进行配置以选择使用 Jedis 或 Lettuce 服务驱动。

5.2.1 使用 Jedis
复制代码
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    @Configuration
    public class RedisConfig {
    
    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName("localhost");
        factory.setPort(6379);
        return factory;
    }
    
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        return template;
    }
    }
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    AI写代码
5.2.2 使用 Lettuce
复制代码
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    @Configuration
    public class RedisConfig {
    
    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        LettuceConnectionFactory factory = new LettuceConnectionFactory();
        factory.setHostName("localhost");
        factory.setPort(6379);
        return factory;
    }
    
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        return template;
    }
    }
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    AI写代码
5.3 使用 RedisTemplate

在你的服务类中,你可以注入 RedisTemplate 并使用它来操作 Redis。

复制代码
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.stereotype.Service;
    
    @Service
    public class RedisService {
    
    private final RedisTemplate<String, Object> redisTemplate;
    
    @Autowired
    public RedisService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    
    public void setKeyValue(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }
    
    public String getKeyValue(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }
    
    public void deleteKey(String key) {
        redisTemplate.delete(key);
    }
    }
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    AI写代码
5.4 切换客户端

要更换Redis客户端(从Jedis到Lettuce或反之亦然),只需修改RedisConfig类中的redisConnectionFactory方法即可。例如,如目前采用的是Jedis,则想要转换到Lettuce时,请将该方法改为返回'LettuceConnectionFactory'。

5.5 配置文件

你也可以利用配置文件来设置 Redis 连接的相关参数,并且这种做法可以让您更加便捷地进行切换和管理各项配置设置

application.properties
复制代码
    # Jedis 配置
    spring.redis.host=localhost
    spring.redis.port=6379
    
    # Lettuce 配置
    # spring.redis.lettuce.pool.max-active=8
    # spring.redis.lettuce.pool.max-wait=-1
    # spring.redis.lettuce.pool.max-idle=8
    # spring.redis.lettuce.pool.min-idle=0
    
    
      
      
      
      
      
      
      
      
      
    
    AI写代码

借助 Spring Data Redis,在 Spring 项目中你可以方便地整合和转换 Jedis 和 Lettuce。无论选择使用 Jedis 还是 Lettuce,在配置 RedisConnectionFactory 后都能实现。这种方法不仅简化了配置步骤,并且增强了代码的可维护性和灵活性。

精彩专栏推荐订阅:下方有多个专栏您可以选择阅读:
✅ 华为OD机试真题集(A/B卷)及面试指导
✅ 精选一百个Java项目实践案例
✅ 面试中需注意避免的常见问题与误区
✅ 那些不可或缺的核心代码
✅ 带您手撕Spring框架核心技术
✅ Java入门必看教程

在这里插入图片描述

全部评论 (0)

还没有任何评论哟~