Springboot整合redis集群相关配置详解

本文详细介绍了如何在Springboot项目中整合Redis集群,包括引入starter、配置yaml文件以实现Lettuce连接池,并解析了StringRedisTemplate和RedisTemplate的区别,以及它们各自的操作方法,如opsForValue、opsForHash等。
摘要由CSDN通过智能技术生成

springboot整合redis

官方配置

# common spring boot settings
spring.redis.database=
spring.redis.host=
spring.redis.port=
spring.redis.password=
spring.redis.ssl=
spring.redis.timeout=
spring.redis.cluster.nodes=
spring.redis.sentinel.master=
spring.redis.sentinel.nodes=
# Redisson settings
#path to config - redisson.yaml
spring.redis.redisson.config=classpath:redisson.yaml

以上是官方的配置:
开始整合
注:redis集群创建相关请自行百度

1 引入starter
测试所用版本

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId&
  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是一个简单的 SpringBoot 整合 Redis 集群的代码示例: 1. 添加 Redis 依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置 Redis 集群 在 application.properties 文件中添加以下配置: ```properties # 集群节点 spring.redis.cluster.nodes=redis://localhost:7001,redis://localhost:7002,redis://localhost:7003,redis://localhost:7004,redis://localhost:7005,redis://localhost:7006 # 连接超时时间 spring.redis.timeout=10000 # 最大重定向次数 spring.redis.cluster.max-redirects=3 ``` 3. 编写 RedisTemplate 配置类 ```java @Configuration public class RedisConfig { @Autowired private RedisConnectionFactory redisConnectionFactory; @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); // 设置序列化方式 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } } ``` 4. 使用 RedisTemplate 操作 Redis ```java @Service public class RedisService { @Autowired private RedisTemplate<String, Object> redisTemplate; public void set(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } } ``` 以上就是一个简单的 SpringBoot 整合 Redis 集群的代码示例。需要注意的是,Redis 集群配置方式可能因版本而异,请根据实际情况进行调整。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值