SpringBoot篇之集成Jedis、Lettuce、Redisson

news2024/10/5 5:14:53

在这里插入图片描述

目录

  • 前言
  • 一、详解Jedis、Lettuce 和 Redisson的区别
  • 二、SpringBoot集成
    • 2.1 集成Jedis
    • 2.2 集成Lettuce
    • 2.3 集成Redisson
  • 总结


前言

大家好,我是AK,最近在做新项目,基于旧项目框架修改,正好最近也在整理springboot相关知识,项目中用到Redis,因此整理出来,帮助需要的小伙伴搞清楚到底选择哪个Redis客户端库。


一、详解Jedis、Lettuce 和 Redisson的区别

Jedis、Lettuce 和 Redisson 都是 Java 中与 Redis 数据库进行交互的客户端库。它们分别有各自的特点和用途。

1. Jedis:

Jedis 是一个常用的 Redis 客户端,通过直接操作 Redis 的命令实现与数据库的交互。
Jedis 是单线程的,即在同一时间只能处理一个命令请求。这使得它在单线程环境下非常高效,并且适合于并发请求较少的情况。
Jedis 使用简单、轻量,并且易于上手。

2. Lettuce:

Lettuce 是一个基于异步、事件驱动的 Redis 客户端。
Lettuce 是基于 Netty 框架实现的,它使用异步非阻塞方式与 Redis 进行通信,并支持连接池和发布/订阅模式。
Lettuce 支持并发请求和连接自动管理,适合处理高并发的环境。
Lettuce 提供更多的配置选项和 Redis 特性的支持。

3. Redisson:

Redisson 是一个基于 Lettuce 和 Netty 的 Redis 客户端和数据结构库,提供了丰富的分布式和集群功能。
Redisson 提供了更高层次的抽象,使开发者更容易使用 Redis 的分布式锁、分布式集合、分布式队列等功能。
Redisson 支持集群模式、主从复制和哨兵模式,并提供了许多分布式解决方案和优化的数据结构。
性能方面,Jedis 和 Lettuce 在不同的场景下可能会有不同的表现。由于 Jedis 是单线程的,适合于非常低的并发环境。而 Lettuce 通过其异步非阻塞的网络处理方式,可以更好地支持高并发环境。Redisson 则在性能方面与 Lettuce 类似,但它更注重于分布式功能和数据结构的操作。

总结来说,Jedis 是一个简单、轻量的 Redis 客户端,适用于单线程环境下的低并发场景;Lettuce 是一个基于异步、事件驱动的 Redis 客户端,适用于高并发场景,并提供了更多的配置选项和功能支持;Redisson 是一个基于 Lettuce 和 Netty 的 Redis 客户端和数据结构库,提供了丰富的分布式和集群功能,并重点关注分布式解决方案和数据结构的优化。在选择合适的客户端时,需要根据具体需求、场景和性能要求进行综合考虑。

二、SpringBoot集成

2.1 集成Jedis

要在Spring Boot中集成Jedis,您可以按照以下步骤进行操作:

添加依赖:打开项目的 pom.xml 文件,并添加 Jedis 的依赖。您可以在 标签下添加以下代码:

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.11.0</version>
</dependency>

配置 Redis 连接:在 Spring Boot 的配置文件(application.properties 或 application.yml)中,添加 Redis 的连接配置,包括主机、端口、密码等。例如,在 application.properties 文件中,您可以添加以下代码:

Redis 连接配置

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=your_password (如果有密码的话)

创建 Jedis 实例:在 Java 代码中,您可以创建 Jedis 实例来与 Redis 进行交互。可以通过在需要使用的类中注入 JedisPool 对象,并使用它来获取 Jedis 实例。示例代码如下:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {

    @Autowired
    private RedisProperties redisProperties;

    @Bean
    public JedisPool jedisPool() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(10);

        JedisPool jedisPool = new JedisPool(poolConfig, redisProperties.getHost(), redisProperties.getPort(), redisProperties.getTimeout(), redisProperties.getPassword());

        return jedisPool;
    }

    @Bean
    public Jedis jedis(JedisPool jedisPool) {
        return jedisPool.getResource();
    }
}

这是一个 Redis 配置类的示例。您可以根据自己的需求进行相关配置,并在需要使用 Jedis 的地方注入 Jedis 对象。

使用 Jedis 进行操作:现在您可以在其他类中使用注入的 Jedis 对象来执行 Redis 操作了。通过调用 Jedis 对象提供的方法,您可以执行各种 Redis 命令。以下是一个简单的示例:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

@Service
public class RedisService {

    @Autowired
    private Jedis jedis;

    public void set(String key, String value) {
        jedis.set(key, value);
    }

    public String get(String key) {
        return jedis.get(key);
    }
}

在上述示例中,我们注入了 Jedis 对象,并使用 set 和 get 方法对 Redis 进行设置和获取操作。

这样,您就成功地将 Jedis 集成到 Spring Boot 中了。您可以根据自己的需要进行更多的操作和配置。记得在完成后适当关闭 Jedis 连接以及释放资源。

2.2 集成Lettuce

要在Spring Boot中集成Lettuce,您可以按照以下步骤进行操作:

添加依赖:打开项目的 pom.xml 文件,并添加 Lettuce 的依赖。您可以在 标签下添加以下代码:

<dependency>
    <groupId>io.lettuce</groupId>
    <artifactId>lettuce-core</artifactId>
    <version>6.1.3.RELEASE</version>
</dependency>

配置 Redis 连接:在 Spring Boot 的配置文件(application.properties 或 application.yml)中,添加 Redis 的连接配置,包括主机、端口、密码等。例如,在 application.properties 文件中,您可以添加以下代码:

Redis 连接配置

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=your_password (如果有密码的话)
spring.redis.lettuce.pool.max-active=10
创建 Lettuce 实例:在需要使用 Redis 的代码中,您可以使用 LettuceConnectionFactory 来创建 Lettuce 的连接工厂,并配置连接池。示例代码如下:
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;

@Configuration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.lettuce.pool.max-active}")
    private int maxActive;

    @Autowired(required = false)
    private ClientResources clientResources;

    @Bean(destroyMethod = "shutdown")
    public ClientResources clientResources() {
        return DefaultClientResources.create();
    }

    @Bean
    public RedisConnectionFactory lettuceConnectionFactory() {
        RedisURI redisURI = RedisURI.builder()
                .withHost(this.host)
                .withPort(this.port)
                .withPassword(this.password)
                .build();

        LettucePoolingClientConfiguration lettucePoolingClientConfiguration = LettucePoolingClientConfiguration.builder()
                .clientResources(this.clientResources)
                .poolConfig(getDefaultPoolConfig())
                .build();

        RedisClient redisClient = RedisClient.create(redisURI);
        LettuceClientConfiguration lettuceClientConfiguration = LettucePoolingClientConfiguration.builder().poolConfig(getDefaultPoolConfig())
                .commandTimeout(redisClient.getOptions().getTimeout())
                .build();
        
        LettuceConnectionFactory factory = new LettuceConnectionFactory(redisClient, lettucePoolingClientConfiguration);
        factory.setShareNativeConnection(false);

        return factory;
    }

    private GenericObjectPoolConfig<?> getDefaultPoolConfig() {
        GenericObjectPoolConfig<?> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(this.maxActive);
        return config;
    }
}

在上述示例中,我们通过 LettucePoolingClientConfiguration 和 RedisURI 配置了 Lettuce 的连接和连接池。在需要使用 Redis 的地方,只需注入 RedisConnectionFactory 对象即可。

使用 Lettuce 进行操作:现在您可以在其他类中使用注入的 RedisConnectionFactory 对象来执行 Redis 操作了。Spring Boot 提供了各种 RedisTemplate 作为默认的 Redis 操作模板,您还可以使用 ReactiveRedisTemplate 进行响应式操作。以下是一个简单的示例:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class RedisService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }
}

在上述示例中,我们注入了 RedisTemplate 对象,并使用它来执行 Redis 的 set 和 get 操作。

这样,您就成功地将 Lettuce 集成到 Spring Boot 中了。您可以根据自己的需要进行更多的操作和配置。记得在完成后适当关闭 Redis 连接以及释放资源。

2.3 集成Redisson

要在Spring Boot中集成Redisson,您可以按照以下步骤进行操作:

添加依赖:打开项目的 pom.xml 文件,并添加 Redisson 的依赖。您可以在 标签下添加以下代码:

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.16.1</version>
</dependency>

配置 Redisson:在 Spring Boot 的配置文件(application.properties 或 application.yml)中,添加 Redisson 的配置。例如,在 application.properties 文件中,您可以添加以下代码:

Redisson 配置

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=your_password (如果有密码的话)

使用 Redisson 进行操作:您可以在需要使用 Redis 的代码中注入 RedissonClient 对象,并使用它来执行 Redis 操作。以下是一个简单的示例:

import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RedisService {

    @Autowired
    private RedissonClient redissonClient;

    public void set(String key, String value) {
        redissonClient.getBucket(key).set(value);
    }

    public String get(String key) {
        return (String) redissonClient.getBucket(key).get();
    }
}

在上述示例中,我们注入了 RedissonClient 对象,并使用它来执行 Redis 的 set 和 get 操作。

这样,您就成功地将 Redisson 集成到 Spring Boot 中了。Redisson 提供了各种功能强大的API,您可以根据自己的需要进行更多的操作和配置。记得在完成后适当关闭 Redis 连接以及释放资源。


总结

最后如果还是不清楚选择哪个,推荐使用Lettuce或Redisson,如果是单体应用选Lettuce,分布式场景就选择Redisson。




                                                                                                         ---- 永不磨灭的番号:我是AK



在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1085240.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

C语言系统化精讲(四): 条件判断语句

文章目录 一、if语句二、if…else语句三、else if语句四、if语句的嵌套五、条件运算符六、switch语句的基本形式七、多路开关模式的switch语句八、if…else语句和switch语句的区别 当我们是儿童时&#xff0c;父母就告诉我们记住这句 红灯停&#xff0c;绿灯行&#xff0c;黄灯…

JTS:11 Overlaps 部分重叠

这里写目录标题 版本代码1 多点与多点2 线与线3 面与面 版本 org.locationtech.jts:jts-core:1.19.0 链接: github 代码 /*** 部分重叠*/ public class GeometryOverlaps {private final GeometryFactory geometryFactory new GeometryFactory();private static final Logg…

提升自动化测试效率的秘密武器——Allure Report

一.使用 Allure2 运行方式-Python # --alluredir 参数生成测试报告。 # 在测试执行期间收集结果 pytest [测试用例/模块/包] --alluredir./result/ (—alluredir这个选项 用于指定存储测试结果的路径)# 生成在线的测试报告 allure serve ./result二.使用 Allure2 运行方式-Ja…

TCP/IP(十四)流量控制

一 流量控制 说明&#xff1a; 本文只是原理铺垫,没有用tcpdumpwiresahrk鲜活的案例讲解,后续补充 ① 基本概念 流量控制: TCP 通过接受方实际能接收的数据量来控制发送方的窗口大小 ② 正常传输过程 背景:1、客户端是接收方,服务端是发送方 --> 下载2、假设接收窗…

Vue绑定样式

一、绑定class样式 语法格式&#xff1a; :class "属性名" &#xff08;一&#xff09;字符串写法 该写法适用于样式的类名不确定&#xff0c;需要动态指定的场景 我们用如下的CSS样式进行操作演示 我们要完成点击按钮改变CSS样式的操作&#xff0c;如下图代码所…

33.高等数学

一、函数与极限。 &#xff08;1&#xff09;函数。 1.平方根&#xff1a;有正负号。 2.算术平方根&#xff1a;算术平方根都是正数。 3.复数&#xff1a;是由实部和虚部组成的数&#xff0c;可以表示为abi 的形式&#xff0c;其中 a 是实部&#xff0c;b 是虚部。如果虚部…

检验科LIS系统源码,多家二甲医院实际使用,三年持续优化和运维,系统稳定可靠

检验科LIS系统源码&#xff0c;Client/Server架构SaaS服务模式的LIS系统全套源码&#xff0c;自主版权&#xff0c;有演示。 LIS系统&#xff0c;专为医院检验科设计的一套实验室信息系统。它是以数据库为核心&#xff0c;将实验仪器与电脑连接成网&#xff0c;基础功能包括病人…

C# 中大小端Endian

大小端可以找下资料很多&#xff0c;都是文字的。我每次遇到大小端问题就会搜资料&#xff0c;总是记不住。我自己用用图片记录一下&#xff0c;以备直观的从内存中看到。 在C#中可以用BitConverter.IsLittleEndian来查询。 几个数字在内存中 我们来观察一下&#xff0c;我的…

小程序中如何设置所服务地区的时区

在全球化的背景下&#xff0c;小程序除了在中国使用外&#xff0c;还为海外的华人地区提供服务。例如我们采云小程序为泰国、阿根廷、缅甸等国家的商家就提供过微信小程序。这些商家开通小程序&#xff0c;为本地的华人提供服务。但通常小程序的开发者/服务商位于中国&#xff…

Java多线程篇(10)——BlockingQueue(数组,链表,同步阻塞队列)

文章目录 1、ArrayBlockingQueue2、LinkedBlockingQueue3、SynchronousQueue3.1、transfer 公平实现&#xff08;队列&#xff09;3.2、transfer 非公平实现&#xff08;栈&#xff09; 1、ArrayBlockingQueue put public void put(E e) throws InterruptedException {Objects…

小程序:下拉刷新+上拉加载+自定义导航栏

下拉刷新 &#xff1a; <scroll-view scroll-y"true" 允许纵向滚动 refresher-enabled"true" 开启自定义下拉刷新 默认为false :refresher-triggered&quo…

从读不完一篇文章,到啃下20万字巨著,大模型公司卷起“长文本”

点击关注 文丨郝 鑫 编丨刘雨琦 4000到40万token&#xff0c;大模型正在以“肉眼可见”的速度越变越“长”。 长文本能力似乎成为象征着大模型厂商出手的又一新“标配”。 国外&#xff0c;OpenAI经过三次升级&#xff0c;GPT-3.5上下文输入长度从4千增长至1.6万token&…

MySQL常用命令01

今天开始&#xff0c;每天总结一点MySQL相关的命令&#xff0c;方便大家后期熟悉。 1.命令行登录数据库 mysql -H IP地址 -P 端口号 -u 用户名 -p 密码 数据库名称 -h 主机IP地址 登录本机 localhost或127.0.0.1 -P 数据库端口号 Mysql默认是3306 -u 用户名 -p 密码 …

nodejs+vue+elementui医院挂号预约管理系统4n9w0

前端技术&#xff1a;nodejsvueelementui 前端&#xff1a;HTML5,CSS3、JavaScript、VUE 1、 node_modules文件夹(有npn install Express 框架于Node运行环境的Web框架, 开发语言 node.js 框架&#xff1a;Express 前端:Vue.js 数据库&#xff1a;mysql 数据库工具&#xff…

公司寄件管理教程

不少企业为了规范因公寄件的管理&#xff0c;节约企业的快递成本&#xff0c;最终简化企业内部办公流程&#xff0c;提升企业整体办公效率&#xff0c;在因公寄件达到一定量的时候&#xff0c;都会推出或繁或简的“公司寄件管理制度”。 所谓的“或繁或简”。是根据企业的寄件场…

前端练习项目(附带页面psd图片及react源代码)

一、前言 相信很多学完前端的小伙伴都想找个前端项目练练手&#xff0c;检测自己的学习成果。但是现在很多项目市面上都烂大街了。今天给大家推荐一个全新的项目——电子校园 项目位置&#xff1a;https://github.com/v5201314/eSchool 二、项目介绍(部分页面展示)&#xff…

C++QT-day6

/*定义一个基类 Animal&#xff0c;其中有一个虛函数perform&#xff08;)&#xff0c;用于在子类中实现不同动物的表演行为。*/ #include <iostream> using namespace std; class Animal //封装Animal类&#xff08;基类&#xff09; { private:string person; public:A…

力扣:130. 被围绕的区域(Python3)

题目&#xff1a; 给你一个 m x n 的矩阵 board &#xff0c;由若干字符 X 和 O &#xff0c;找到所有被 X 围绕的区域&#xff0c;并将这些区域里所有的 O 用 X 填充。 来源&#xff1a;力扣&#xff08;LeetCode&#xff09; 链接&#xff1a;力扣&#xff08;LeetCode&#…

在线免费AI绘画工具

体验地址 点我进行AI绘画 使用 选择以文搜图进行绘画 提问 介绍 首先&#xff0c;我们来了解一下ChatGPT。作为一个人工智能语言模型&#xff0c;它可以自动回答你的问题、提供信息&#xff0c;并与你进行流畅的对话。它通过大量的训练数据和机器学习算法&#xff0c;学…

react–antd 实现TreeSelect树形选择组件,实现点开一层调一次接口

效果图: 注意: 当选择“否”&#xff0c;开始调接口&#xff0c;不要把点击调接口写在TreeSelect组件上&#xff0c;这样会导致问题出现&#xff0c;没有层级了 部分代码: