Redisson(二)SpringBoot集成Redisson

目录

一、Redis单例模式

二、Redis哨兵模式

三、Redis集群模式

 四、主从模式 

五、兼容多种模式的配置(重点)

1、pom

2、配置文件

(1)application.properties

(2)application-dev.properties

(3) application-prod.properties

3、Java配置类

4、应用


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

支持Redis多种连接模式,这里以RedissonClient工具为例

一、Redis单例模式

#单机模式
#Redis url should start with redis:// or rediss:// (for SSL connection)
my.redisson.address = redis://127.0.0.1:6379
my.redisson.password = wtyy

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class RedissionConfig {@Value("${my.redisson.address}")private String address;@Value("${my.redisson.password}")private String password;/*** 所有对Redisson的使用都是通过RedissonClient对象*/@Bean(destroyMethod = "shutdown")public RedissonClient redissonClient(){// 创建配置 指定redis地址及节点信息Config config = new Config();config.useSingleServer().setAddress(address);//.setPassword(password);// 根据config创建出RedissonClient实例RedissonClient redissonClient = Redisson.create(config);return redissonClient;}
}

二、Redis哨兵模式

my.redisson.sentinel.schema=
my.redisson.sentinel.address = redis://xxx.xx.xxx1:19601,redis://xxx.xx.xxx2:19601,redis://xxx.xx.xxx3:19601
my.redisson.sentinel.password = N5WAXX4z9qw
my.redisson.sentinel.master = master-test
my.redisson.sentinel.database = 10

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class RedissionConfig {@Value("${my.redisson.sentinel.address}")private String address;@Value("${my.redisson.sentinel.password}")private String password;@Value("${my.redisson.sentinel.master}")private String master;@Value("${my.redisson.sentinel.database}")private Integer dataBase;@Value("${my.redisson.sentinel.schema}")private String schema;/*** 所有对Redisson的使用都是通过RedissonClient对象*/@Bean(destroyMethod = "shutdown")public RedissonClient redissonClient(){Config config = new Config();config.useSentinelServers().setScanInterval(2000) // cluster state scan interval in milliseconds.addSentinelAddress(address.split(",")).setCheckSentinelsList(false).setMasterName(master).setPassword(password).setDatabase(dataBase);RedissonClient redissonClient = Redisson.create(config);return redissonClient;}
}

三、Redis集群模式

    Config config = new Config();config.useClusterServers().setScanInterval(2000) // cluster state scan interval in milliseconds.addNodeAddress("redis://127.0.0.1:7000", "redis://127.0.0.1:7001").addNodeAddress("redis://127.0.0.1:7002");RedissonClient redisson = Redisson.create(config);

 四、主从模式 

    Config config = new Config();config.useMasterSlaveServers().setMasterAddress("redis://127.0.0.1:6379").addSlaveAddress("redis://127.0.0.1:6389", "redis://127.0.0.1:6332", "redis://127.0.0.1:6419").addSlaveAddress("redis://127.0.0.1:6399");RedissonClient redisson = Redisson.create(config);

五、兼容多种模式的配置(重点)

从上面可以看到,不同的redis模式有不同的连接配置方式,如果连接变更,配置代码也要跟着变更,不够灵活,再比如有多套环境,测试环境和生产环境使用的是不同的redis模式,所以需要考虑配置兼容问题。下面的配置适用于所有模式。

1、pom

因为使用到了 RedisProperties,所以需要引入 spring-boot-starter-data-redis

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>redis-demo</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.2.4</version><relativePath/></parent><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.redisson</groupId><artifactId>redisson</artifactId><version>3.26.0</version></dependency><!--连接池依赖--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.11.1</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!--hutool工具--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.15</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.83</version></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.10.1</version></dependency></dependencies></project>
2、配置文件

 按照 org.springframework.boot.autoconfigure.data.redis.RedisProperties 规则配置。源码:

package org.springframework.boot.autoconfigure.data.redis;@ConfigurationProperties(prefix = "spring.data.redis"
)
public class RedisProperties {private int database = 0;private String url;private String host = "localhost";private String username;private String password;private int port = 6379;private Duration timeout;private Duration connectTimeout;private String clientName;private ClientType clientType;private Sentinel sentinel;private Cluster cluster;private final Ssl ssl = new Ssl();private final Jedis jedis = new Jedis();private final Lettuce lettuce = new Lettuce();......
}

这里有两套环境:dev和prod

(1)application.properties
spring.profiles.active=dev
(2)application-dev.properties
spring.data.redis.host=127.0.0.1
spring.data.redis.port=6379
spring.data.redis.password=
spring.data.redis.lettuce.pool.max-active=8
spring.data.redis.lettuce.pool.max-wait=-1
spring.data.redis.lettuce.pool.max-idle=8
spring.data.redis.lettuce.pool.min-idle=0
spring.data.redis.lettuce.pool.enabled=true
spring.data.redis.lettuce.pool.time-between-eviction-runs=30s
(3) application-prod.properties
spring.data.redis.cluster.nodes=xxx.xxx.xx.xxx:6379
spring.data.redis.cluster.max-redirects=3
spring.data.redis.timeout=60S
spring.data.redis.lettuce.pool.max-wait=2S
spring.data.redis.lettuce.pool.max-active=1200
spring.data.redis.lettuce.pool.max-idle=400
spring.data.redis.lettuce.pool.min-idle=50
# spring.redis.lettuce.pool.time-between-eviction-runs=200
spring.data.redis.lettuce.pool.enabled=true
spring.data.redis.lettuce.pool.time-between-eviction-runs=30s
spring.data.redis.lettuce.cluster.refresh.adaptive=true
spring.data.redis.lettuce.cluster.refresh.period=60s
3、Java配置类

读取配置文件中 spring.data.redis 开头的配置,并加以判断。

package org.example.config;import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;@Slf4j
@Configuration
public class RedissonConfig {@AutowiredRedisProperties redisProperties;private static final String REDIS_PROTOCOL_PREFIX = "redis://";private static final String REDISS_PROTOCOL_PREFIX = "rediss://";@Bean(destroyMethod = "shutdown")public RedissonClient redisson() {Config config;Method clusterMethod = ReflectionUtils.findMethod(RedisProperties.class, "getCluster");Method timeoutMethod = ReflectionUtils.findMethod(RedisProperties.class, "getTimeout");Object timeoutValue = ReflectionUtils.invokeMethod(timeoutMethod, redisProperties);int timeout;if (null == timeoutValue) {timeout = 10000;} else if (!(timeoutValue instanceof Integer)) {Method millisMethod = ReflectionUtils.findMethod(timeoutValue.getClass(), "toMillis");timeout = ((Long) ReflectionUtils.invokeMethod(millisMethod, timeoutValue)).intValue();} else {timeout = (Integer) timeoutValue;}if (redisProperties.getSentinel() != null) {Method nodesMethod =ReflectionUtils.findMethod(RedisProperties.Sentinel.class, "getNodes");Object nodesValue =ReflectionUtils.invokeMethod(nodesMethod, redisProperties.getSentinel());String[] nodes;if (nodesValue instanceof String) {nodes = convert(Arrays.asList(((String) nodesValue).split(",")));} else {nodes = convert((List<String>) nodesValue);}config = new Config();config.useSentinelServers().setMasterName(redisProperties.getSentinel().getMaster()).addSentinelAddress(nodes).setDatabase(redisProperties.getDatabase()).setConnectTimeout(timeout).setPassword(redisProperties.getPassword());} else if (clusterMethod != null&& ReflectionUtils.invokeMethod(clusterMethod, redisProperties) != null) {Object clusterObject = ReflectionUtils.invokeMethod(clusterMethod, redisProperties);Method nodesMethod = ReflectionUtils.findMethod(clusterObject.getClass(), "getNodes");List<String> nodesObject =(List) ReflectionUtils.invokeMethod(nodesMethod, clusterObject);String[] nodes = convert(nodesObject);config = new Config();config.useClusterServers().addNodeAddress(nodes).setConnectTimeout(timeout).setPassword(redisProperties.getPassword());} else {config = new Config();String prefix = REDIS_PROTOCOL_PREFIX;Method method = ReflectionUtils.findMethod(RedisProperties.class, "isSsl");if (method != null && (Boolean) ReflectionUtils.invokeMethod(method, redisProperties)) {prefix = REDISS_PROTOCOL_PREFIX;}String password =StringUtils.isBlank(redisProperties.getPassword())? null: redisProperties.getPassword();config.useSingleServer().setAddress(prefix + redisProperties.getHost() + ":" + redisProperties.getPort()).setConnectTimeout(timeout).setDatabase(redisProperties.getDatabase()).setPassword(password);}return Redisson.create(config);}private String[] convert(List<String> nodesObject) {List<String> nodes = new ArrayList<String>(nodesObject.size());for (String node : nodesObject) {if (!node.startsWith(REDIS_PROTOCOL_PREFIX)&& !node.startsWith(REDISS_PROTOCOL_PREFIX)) {nodes.add(REDIS_PROTOCOL_PREFIX + node);} else {nodes.add(node);}}return nodes.toArray(new String[nodes.size()]);}
}

这里用了反射,其实RedisProperties对象已经拿到了,直接从 redisProperties中get也是可以的:

RedisProperties.Cluster cluster = redisProperties.getCluster();
4、应用
import com.alibaba.fastjson.JSON;
import org.example.dto.UserDTO;
import org.example.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
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;@SpringBootTest(classes = {Main.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class RedissonTest {@Autowiredprivate RedissonClient redissonClient;@Testpublic void  testString(){RBucket<Object> bucket = redissonClient.getBucket("test");bucket.set("这是value");System.out.println(bucket.get());}
}
5、与RedisTemplate并存使用

这个demo引入了  spring-boot-starter-data-redis,所以可以直接使用RedisTemplate:

@SpringBootTest(classes = {Main.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class MyTest {@Autowiredprivate StringRedisTemplate stringRedisTemplate;@Autowiredprivate UserService userService;@Testpublic void  testString(){String key = "string-name";//存String value = "这是value123";stringRedisTemplate.opsForValue().set(key,value);//取Object valueObj = stringRedisTemplate.opsForValue().get(key);System.out.println("value为:" + valueObj);}
}

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

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

相关文章

eclipse下载与安装(汉化教程)超详细

目录 一、下载eclipse安装包 三、配置eclipse 代码自动补全功能 安装汉化包 中英文切换 四、用eclipse写hello world 一、下载eclipse安装包 1、首先进入 eclipse官网 如下&#xff1a; 2、这里面有很多版本&#xff1b;我们小白一般选择第二个&#xff0c;向下滑动&…

【Kettle的安装与使用】使用Kettle实现mysql和hive的数据传输(使用Kettle将mysql数据导入hive、将hive数据导入mysql)

文章目录 一、安装1、解压2、修改字符集3、启动 二、实战1、将hive数据导入mysql2、将mysql数据导入到hive 一、安装 Kettle的安装包在文章结尾 1、解压 在windows中解压到一个非中文路径下 2、修改字符集 修改 spoon.bat 文件 "-Dfile.encodingUTF-8"3、启动…

Nop平台核心代码阅读导引

Nop平台核心引擎的实现代码都很简短&#xff0c;一般模块的核心代码量都是5000行左右的量级&#xff0c;只有ORM比较复杂一些&#xff0c;1万多行。 虽然代码很短&#xff0c;实际实现的功能特性却很多&#xff0c;要把所有细节设计都介绍到&#xff0c;文档量还是不小。建议有…

RHCE笔记-DNS服务器

一.DNS简介 DNS&#xff08;域名系统&#xff09;是一种互联网服务&#xff0c;负责将我们熟悉的域名&#xff08;比如 www.example.com&#xff09;转换为计算机能理解的IP地址&#xff08;比如 192.0.2.1&#xff09;。这样&#xff0c;当你在浏览器中输入网址时&#xff0c;…

利用QGIS工具手动绘制线轨迹并生成地理信息geojson文件

前端想要获得一个完整的shp文件或者geojson的地理信息文件&#xff0c;可以利用QGIS工具手动绘制你想要的数据点位&#xff0c;然后导出图层生成对应的文件即可。 1、新建临时图层 选择线图层&#xff0c;点击ok创建临时图层。 2、绘制线图层 在工具栏中选择添加线要素&#…

关于IO多路复用

先说总结 IO 多路复用的概念可以从网络 IO 的阻塞模型谈起。早期网络编程通常依赖阻塞的 read 函数读取数据&#xff0c;这会导致线程被阻塞&#xff0c;无法处理其他任务。为避免线程阻塞&#xff0c;常使用多线程来处理新的客户端连接。然而&#xff0c;随着客户端连接数的增…

面试记录(1)

java中的抽象类和接口的区别&#xff1a; 相同点 (1) 都可以被继承 (2) 都不能被实例化 (3) 都可以包含方法声明 (4) 派生类必须实现未实现的方法 不同点 1.关键字不同&#xff1a; ​ ① 继承抽象类的关键字是extends&#xff0c;而实现接口的关键字是implements&#xff1b;…

【rust实战】rust博客系统3_项目目录结构及文件目录引入

项目中如何文件目录分层 blog Cargo.toml --依赖项 src main.rs --主文件 handlers --处理用户请求的函数 user_handler.rs mod.rs models --定义用户模型 user.rs mod.rs routes --定义路由 user_ro…

构建您自己的 RAG 应用程序:使用 Ollama、Python 和 ChromaDB 在本地设置 LLM 的分步指南

在数据隐私至关重要的时代&#xff0c;建立自己的本地语言模型 &#xff08;LLM&#xff09; 为公司和个人都提供了至关重要的解决方案。本教程旨在指导您完成使用 Ollama、Python 3 和 ChromaDB 创建自定义聊天机器人的过程&#xff0c;所有这些机器人都托管在您的系统本地。以…

聊聊Web3D 发展趋势

随着 Web 技术的不断演进&#xff0c;Web3D 正逐渐成为各行业数字化的重要方向。Web3D 是指在网页中展示 3D 内容的技术集合。近年来&#xff0c;由于 WebGL、WebGPU 等技术的发展&#xff0c;3D 内容已经能够直接在浏览器中渲染&#xff0c;为用户提供更加沉浸、互动的体验。以…

同一个页面击穿element样式后,会影响同样组件的使用

问题&#xff1a;同一个页面里&#xff0c;我用deep击穿第一个dialog后&#xff0c;怎么不影响第二个dialog。 解决&#xff1a;使用更具体的选择器 给新的对话框一个特定的类名或者ID&#xff0c;然后为这个类名或ID下的 .el-dialog 使用 :deep() 选择器。这样&#xff0c;样式…

电科金仓(人大金仓)更新授权文件(致命错误: XX000: License file expired.)

问题:电科金仓(人大金仓)数据库链接异常,重启失败,查看日志如下: 致命错误: XX000: License file expired. 位置: PostmasterMain, postmaster.c:725 解决方法: 一、下载授权文件 根据安装版本在官网下载授权文件(电科金仓-成为世界卓越的数据库产品与服务提供商)…

阿里云ECS访问GitHub解决方案

使用阿里云 ECS 访问 Github 和拉取代码时&#xff0c;速度非常慢&#xff0c;等于不可用。 本解决方案适用于墙内所有云服务器。 修改系统hosts方式 阻碍 GitHub 访问的一般手段是 DNS 污染&#xff0c;可以通过修改hosts的方式暂时缓解。 访问 ipaddress.com,获取github.co…

uniapp的video视频属性打包app后层级过高

问题&#xff1a;在使用uniapp开发APP时&#xff0c;使用video标签显示视频发现H5可以正常展示&#xff0c;但是打包到APP后&#xff0c;它的层级过高&#xff0c;把底部导航都盖住了。 官网说明&#xff1a;uni-app官网 官网给了cover-view组件或plus.nativeObj.view、subNVue…

考研资料分享系统的设计与实现(lw+演示+源码+运行)

摘 要 互联网发展至今&#xff0c;无论是其理论还是技术都已经成熟&#xff0c;而且它广泛参与在社会中的方方面面。它让信息都可以通过网络传播&#xff0c;搭配信息管理工具可以很好地为人们提供服务。针对高校教师成果信息管理混乱&#xff0c;出错率高&#xff0c;信息安全…

[perl] 数组与哈希

数组变量以 符号开始&#xff0c;元素放在括号内 简单举例如下 #!/usr/bin/perl names ("a1", "a2", "a3");print "\$names[0] $names[0]\n"; print "size: ",scalar names,"\n";$new_names shift(names); …

项目符合行业安全标准的必要步骤与实用建议

要保障项目符合行业安全标准&#xff0c;关键在于建立全面的安全管理体系、定期进行风险评估、持续培训员工&#xff0c;以及确保合规性文件和审核流程完整。例如&#xff0c;通过建立合规文件和审核流程&#xff0c;可以系统性地跟踪项目的安全实践和合规性&#xff0c;使安全…

小米15和小米15 Pro区别没那么大,但也得看准再下手

小米15和小米15 Pro区别大总结 接下来&#xff0c;我们将从关键差别等多个方面来分析两个机型的具体区别&#xff08;Ps&#xff1a;只聊不一样的&#xff0c;没提到就是一样的&#xff09;&#xff1a; 关键差别 • 屏幕素质&#xff1a;小米15采用的是6.36英寸1.5K&#xf…

【科研绘图】3DMAX管状图表生成插件TubeChart使用方法

3DMAX管状图表生成插件TubeChart&#xff0c;一款用于制作3D管状图表的工具。可以自定义切片的数量以及随机或指定切片颜色。 【版本要求】 3dMax 2008及更高版本 【安装方法】 TubeChart插件无需安装&#xff0c;使用时直接拖动插件脚本文件到3dMax视口中打开即可&#xff0…

【Python爬虫实战】络爬虫完整指南:从TCP/IP协议到爬虫实践

网络爬虫完整指南&#xff1a;从TCP/IP协议到爬虫实践 什么是TCP/IP协议&#xff1f; TCP/IP协议&#xff08;传输控制协议/互联网协议&#xff09; 是互联网通信的核心协议套件&#xff0c;它定义了设备在互联网上如何通信的规则和方式。TCP/IP协议由多个层组成&#xff0c;其…