实现Redis主从SpringBoot YML配置
一、流程图
gantt
title Redis主从SpringBoot YML配置流程
section 配置
编写YML文件 :done, 2022-01-01, 1d
引入相关依赖 :done, after 编写YML文件, 1d
配置主从服务 :done, after 引入相关依赖, 1d
二、步骤
步骤 | 详细操作 |
---|---|
1. | 编写YML文件 |
2. | 引入相关依赖 |
3. | 配置主从服务 |
三、详细操作
1. 编写YML文件
# application.yml
spring:
redis:
host: localhost
port: 6379
password: password
database: 0
lettuce:
pool:
max-active: 8
max-idle: 8
min-idle: 0
max-wait: -1ms
cluster:
nodes: node1:6379,node2:6379
2. 引入相关依赖
在pom.xml
文件中添加以下依赖:
<!-- Redis依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
3. 配置主从服务
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
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.GenericToStringSerializer;
@Configuration
public class RedisConfig {
@Autowired
private RedisClusterProperties redisClusterProperties;
@Bean
public RedisConnectionFactory redisConnectionFactory() {
RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration(redisClusterProperties.getNodes());
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(clusterConfig);
jedisConnectionFactory.setPassword(redisClusterProperties.getPassword());
jedisConnectionFactory.setTimeout(redisClusterProperties.getTimeout());
return jedisConnectionFactory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory());
template.setKeySerializer(new GenericToStringSerializer<>(Object.class));
template.setValueSerializer(new GenericToStringSerializer<>(Object.class));
return template;
}
}
四、关系图
erDiagram
USER ||--o| ROLE : has
通过以上步骤,你就可以成功实现Redis主从SpringBoot YML配置了。祝贺你!继续加油学习,不断提升自己的技术水平。