Spring Boot集成Redisson详细介绍

news/2025/2/22 3:50:25/

Redisson是一个用于Java的分布式和高可用的Java对象的框架,它基于Redis实现。在Spring Boot应用程序中集成Redisson可以帮助我们更轻松地实现分布式锁、分布式对象、分布式集合等功能。本文将介绍如何在Spring Boot项目中集成Redisson,并展示一些基本用法。

springboot-redisson.jpg

添加依赖

在Spring Boot项目中,打开pom.xml文件并添加以下Redisson的Maven依赖:

<!-- redisson -->
<dependency><groupId>org.redisson</groupId><artifactId>redisson</artifactId><version>3.25.2</version>
</dependency>

添加配置文件

在application.yml文件中添加Redisson的配置信息:

spring:redisson:#  单机模式host: 192.168.10.106port: 6379# 哨兵模式sentinel:master: mymasternodes: 192.168.10.106:6209,192.168.10.106:6219,192.168.10.106:6229# 集群模式cluster: 192.168.10.106:6109,192.168.10.106:6119,192.168.10.106:6129# 密码password: xj2022

注意: 我们如果只有一个redis客户端的话我们在此处只需要配置一种模式,别的配置信息留空即可,我们会通过配置类优先找 哨兵配置,没有的话再找cluster集群配置,没有的话再找单机配置。

添加配置类

在代码中添加配置类RedissonConfig:


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;
import org.redisson.config.ReadMode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
@Slf4j
public class RedissonConfig {@Value("${spring.redisson.sentinel.nodes}")private  String sentinel;@Value("${spring.redisson.sentinel.master}")private String masterName;@Value("${spring.redisson.cluster}")private  String cluster;@Value("${spring.redisson.host}")private String host;@Value("${spring.redisson.port}")private  String port;@Value("${spring.redisson.password}")private String password;private int timeout = 2000;private int scanInterval = 60000;private static String ADDRESS_PREFIX = "redis://";/*** 单机模式*/@Beanpublic RedissonClient initBean() {// 哨兵模式if (StringUtils.isNotBlank(sentinel)) {log.info("redis is sentinel mode");return redissonSentinel();}// 集群模式if (StringUtils.isNotBlank(cluster)) {log.info("redis is cluster mode");return redissonCluster();}// 单机模式if (StringUtils.isNotBlank(host)) {log.info("redis is single mode");return redissonSingle();}log.error("redisson config can not support this redis mode");return null;}/*** 单机模式*/private RedissonClient redissonSingle() {Config config = new Config();String address = ADDRESS_PREFIX+host+":"+port;//设置config.setCodec(new StringCodec())//这是用的集群server.useSingleServer().setAddress(address).setTimeout(timeout).setPassword(password);return Redisson.create(config);}/*** 哨兵模式*/private RedissonClient redissonSentinel() {String[] nodes = sentinel.split(",");//redisson版本是3.5,集群的ip前面要加上“redis://”,不然会报错,3.2版本可不加for(int i=0;i<nodes.length;i++){nodes[i] = ADDRESS_PREFIX+nodes[i];}Config config = new Config();//设置config.setCodec(new StringCodec()).useSentinelServers().setMasterName(masterName).setPassword(password).setTimeout(timeout).addSentinelAddress(nodes)// 在Redisson启动期间启用sentinels列表检查,默认为true,这里我们设置为false,不检查.setCheckSentinelsList(false);return Redisson.create(config);}/*** 集群模式*/private RedissonClient redissonCluster() {String[] nodes = cluster.split(",");//redisson版本是3.5,集群的ip前面要加上“redis://”,不然会报错,3.2版本可不加for(int i=0;i<nodes.length;i++){nodes[i] = ADDRESS_PREFIX+nodes[i];}Config config = new Config();//设置config.setCodec(new StringCodec())//这是用的集群server.useClusterServers()//设置集群状态扫描时间.setScanInterval(scanInterval).addNodeAddress(nodes).setPassword(password).setReadMode(ReadMode.MASTER);;return Redisson.create(config);}}

这样,我们就配置好了redisson,我们可以在代码中使用了。

示例:分布式锁

以下是一个使用redisson 分布式锁的示例代码

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;import java.util.concurrent.TimeUnit;@Service
@Slf4j
public class RedissonTestService {@Resourceprivate RedissonClient redissonClient;//锁过期时间private static final Long LOCK_KEY_TIME = 120L;public void doJobTask() {//定时任务执行周期较短,为防止数据重复修改,加入锁RLock lock = redissonClient.getLock("your_task_name");// 尝试获取锁并设定锁的过期时间boolean acquired = false;try {//获取锁acquired = lock.tryLock(0, LOCK_KEY_TIME, TimeUnit.SECONDS);} catch (InterruptedException e) {log.error("取锁失败");}if (acquired) {try {// 执行业务逻辑}catch (Exception e) {log.error("处理失败");//业务异常处理逻辑}finally {// 释放锁lock.unlock();}} else {// 获取锁失败,说明有其他线程或进程正在处理数据// 可以进行重试或触发告警机制}}}

这只是一个简单的示例,你可以根据需要使用更高级的Redisson功能。

总结

通过集成Redisson,我们可以轻松地实现分布式系统中的各种功能,提高应用程序的可伸缩性和可靠性。我们在生产环境会经常有跨机房使用承载网连接redis的情况,我们后续会在写一篇关于redisson实现承载网转换源码改造的文章。希望本文能够帮助你快速入门Spring Boot集成Redisson,并在实际项目中应用这些功能。


http://www.ppmy.cn/news/1336691.html

相关文章

在Ubuntu环境下搭建小型化Git服务器

对于我们写代码的人来说&#xff0c;git再熟悉不过了&#xff0c;也必不可少&#xff0c;比如像我&#xff0c;在单位写了点东西&#xff0c;晚上回到家有时还要捯饬一下&#xff0c;但电脑带来带去的也麻烦不是&#xff0c;有了私有的Git库&#xff0c;就方便多了&#xff0c;…

jenkins pipeline配置maven可选参数

1、在Manage Jenkins下的Global Tool Configuration下对应的maven项添加我们要用得到的不同版本的maven安装项 2、pipeline文件内容具体如下 我们maven是单一的&#xff0c;所以我们都是配置单选参数 pipeline {agent anyparameters {gitParameter(name: BRANCH_TAG, type: …

mysql之基本查询

基本查询 一、SELECT 查询语句 一、SELECT 查询语句 查询所有列 1 SELECT *FORM emp;查询指定字段 SELECT empno,ename,job FROM emp;给字段取别名 SELECT empno 员工编号 FROM emp; SELECT empno 员工编号,ename 姓名,job 岗位 FROM emp; SELECT empno AS 员工编号,ename …

THM学习笔记——john

John the Ripper是目前最好的哈希破解工具之一。 John基本语法&#xff1a; john [options] [path to file] john&#xff1a;调用John the Ripper程序。 [path to file]&#xff1a;包含你要尝试破解的哈希的文件&#xff0c;如果它们在同一个目录中&#xff0c;你就不需要命名…

USB 设备常见问题

USB 设备常见问题 当涉及到 USB&#xff08;通用串行总线&#xff09;的使用时&#xff0c;可能会遇到一些常见问题。以下是一些常见的 USB 问题及其解决方案&#xff1a; USB 设备无法正常工作&#xff1a;如果 USB 设备无法正常工作&#xff0c;首先确保设备已正确连接至计算…

网站地址怎么改成HTTPS?

现在&#xff0c;所有类型的网站都需要通过 HTTPS 协议进行安全连接&#xff0c;而实现这一目标的唯一方法是使用 SSL 证书。如果您不将 HTTP 转换为 HTTPS&#xff0c;浏览器和应用程序会将您网站的连接标记为不安全。 但用户询问如何将我的网站从 HTTP 更改为 HTTPS。在此页…

翻译: GPT-4 Vision征服LLM幻觉hallucinations 升级Streamlit六

GPT-4 Vision 系列: 翻译: GPT-4 with Vision 升级 Streamlit 应用程序的 7 种方式一翻译: GPT-4 with Vision 升级 Streamlit 应用程序的 7 种方式二翻译: GPT-4 Vision静态图表转换为动态数据可视化 升级Streamlit 三翻译: GPT-4 Vision从图像转换为完全可编辑的表格 升级St…

【Spring实战】32 Spring Boot3 集成 Nacos 服务注册中心 并在 Gateway 网关中应用

文章目录 1. 定义2. 背景3. 功能和特性4. 下载安装5. 服务启动6. 使用示例1&#xff09;服务提供者2&#xff09;服务消费者3&#xff09;测试 7. 代码参考结语 1. 定义 Nacos 是 Dynamic Naming and Configuration Service 的首字母简称&#xff0c;一个更易于构建云原生应用…