Java使用Lettuce客户端在Redis在主从复制模式下命令执行的操作
作者:FserSuN 发布时间:2023-11-28 21:38:19
1 redis主从复制的概念
多机环境下,一个redis服务接收写命令,当自身数据与状态发生变化,将其复制到一个或多个redis。这种模式称为主从复制。在redis中通过命令salveof命令让执行该命令的redis复制另一个redis数据与状态。我们将主服务器称为master,从服务器称为slave。
主从复制保证了网络异常正常时,网络断开重的情况下将数据复制。网络正常时master会通过发送命令保持对slave更新,更新包括客户端的写入,key的过期或被逐出等网络异常,master与slave连接断开一段时间,slave重连上master后会尝试部分重同步,重新获取连接断开期间丢失的命令。当无法进行部分重同步,则会执行全量重同步。
2 为什么需要主从复制
为了保证数据不丢失,有时会用到持久化功能。但这样会增加磁盘IO操作。通过使用主从复制,可以替代持久化并减少IO操作,降低延迟提高性能。
主从模式下,master负责处理写,slave负责读。虽然主从同步会导致在数据存在不一致窗口,但可以增加读操作的吞吐量。主从模式避免了redis单点风险。通过副本提高系统可用性。当master挂掉,从slave中选举新的机器作为master保证系统可用。
3 主从复制配置及原理
主从复制可以分为三个阶段:初始化、同步、命令传播。
初始化:从服务器执行完 slaveof 命令后,slave与master建立socket连接。连接建立完毕后通过ping进行心跳检测,若master正常,则返回响应。如果出现故障收不到响应,那么slave会重新尝试连接master。如果master设置了认证信息,则会再检查认证数据是否正确。如果认证失败,则会报错。
同步:当初始化完毕,master收到slave的数据同步命令后,需要判断是否执行全量同步还是部分同步。
命令传播:同步完成后,master与slave通过心跳检测判断对方是否在线。slave同时向master发送自己复制缓冲区的偏移量。master根据这些请求,判断是否向slave同步新产生的命令。slave收到同步的命令后执行,最终与master保持同步。
4 使用Lettuce在主从模式下执行命令
常用的Java Redis客户端有Jedis、Redission、Lettuce。这里将通过Lettuce来演示主从模式下的读写分离命令执行。
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
下面通过
package redis;
import io.lettuce.core.ReadFrom;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.sync.RedisCommands;
import io.lettuce.core.codec.Utf8StringCodec;
import io.lettuce.core.masterslave.MasterSlave;
import io.lettuce.core.masterslave.StatefulRedisMasterSlaveConnection;
import org.assertj.core.util.Lists;
class MainLettuce {
public static void main(String[] args) {
List<RedisURI> nodes = Lists.newArrayList(
RedisURI.create("redis://localhost:7000"),
RedisURI.create("redis://localhost:7001")
);
RedisClient redisClient = RedisClient.create();
StatefulRedisMasterSlaveConnection<String, String> connection = MasterSlave.connect(
redisClient,
new Utf8StringCodec(), nodes);
connection.setReadFrom(ReadFrom.SLAVE);
RedisCommands<String, String> redisCommand = connection.sync();
redisCommand.set("master","master write test2");
String value = redisCommand.get("master");
System.out.println(value);
connection.close();
redisClient.shutdown();
}
}
补充:Redis 客户端之Lettuce配置使用(基于Spring Boot 2.x)
开发环境:使用Intellij IDEA + Maven + Spring Boot 2.x + JDK 8
Spring Boot 从 2.0版本开始,将默认的Redis客户端Jedis替换问Lettuce,下面描述Lettuce的配置使用。
1.在项目的pom.xml文件下,引入Redis在Spring Boot 下的相关Jar包依赖
properties>
<redisson.version>3.8.2</redisson.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</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.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
</dependencies>
2.在项目的resources目录下,在application.yml文件里添加lettuce的配置参数
#Redis配置
spring:
redis:
database: 6 #Redis索引0~15,默认为0
host: 127.0.0.1
port: 6379
password: #密码(默认为空)
lettuce: # 这里标明使用lettuce配置
pool:
max-active: 8 #连接池最大连接数(使用负值表示没有限制)
max-wait: -1ms #连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 5 #连接池中的最大空闲连接
min-idle: 0 #连接池中的最小空闲连接
timeout: 10000ms #连接超时时间(毫秒)
3.添加Redisson的配置参数读取类RedisConfig
package com.dbfor.redis.config;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
/**
* RedisTemplate配置
* @param connectionFactory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory connectionFactory) {
// 配置redisTemplate
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());//key序列化
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());//value序列化
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
4.构建Spring Boot的启动类RedisApplication
package com.dbfor.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class);
}
}
5.编写测试类RedisTest
package com.dbfor.redis;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
@Component
public class RedisTest {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void set() {
redisTemplate.opsForValue().set("test:set1", "testValue1");
redisTemplate.opsForSet().add("test:set2", "asdf");
redisTemplate.opsForHash().put("hash1", "name1", "lms1");
redisTemplate.opsForHash().put("hash1", "name2", "lms2");
redisTemplate.opsForHash().put("hash1", "name3", "lms3");
System.out.println(redisTemplate.opsForValue().get("test:set"));
System.out.println(redisTemplate.opsForHash().get("hash1", "name1"));
}
}
6.在Redis上查看运行结果
从上图可以看到,Lettuce配置操作数据库成功!
来源:https://blog.csdn.net/Revivedsun/article/details/101157571


猜你喜欢
- 本文实例分析了C#中登录窗体和欢迎窗体关闭方法。分享给大家供大家参考。具体分析如下:在c#的winform编程中,我们经常会做登录窗体或欢迎
- 本文介绍IntelliJ IDEA中Project 窗口的一些设置技巧,参考IntelliJ IDEA 简体中文专题教程,英文好的同学可以查
- 首先我们定义一个可以在运行时动态的找出项目的路径WebAppRootKey,这么做的原因是为了在后面配置log4j输出文件路径的时候能随心配
- Java单例模式的实现,对java 单例模式的几种实现方法进行了整理:单例模式好多书上都是这么写的:public class SingleT
- 一、 序列化和反序列化概念Serialization(序列化)是一种将对象以一连串的字节描述的过程;反序列化deserialization是
- 类与对象:类是抽象的数据类型,对象是抽象的数据类型的具体化。使用new 关键字创建对象,默认初始化为null一个项目只存在一个main方法,
- 需求是需要在TextView前端加入一个标签展示。最终效果图如下:根据效果图,很容易就能想到使用SpannableStringBuilder
- IISExpress 配置允许外部访问详细介绍1.找到IISExpress的配置文件,位于 <文档>/IISExpr
- 概述本文介绍 Spring Boot 项目中整合 ElasticSearch 并实现 CRUD 操作,包括分页、滚动等功能。添加Maven依
- 一、业务背景有些业务请求,属于耗时操作,需要加锁,防止后续的并发操作,同时对数据库的数据进行操作,需要避免对之前的业务造成影响。二、分析流程
- springmvc的图片上传1.导入相应的pom依赖 <dependency> <groupId>co
- springmvc 使用map接收参数开发过程中有时候我们并不知道前端都会传递哪些参数给到后端. 为方便扩展接口功能, 在请求参数不改变的情
- 1.问题描述在一个目录及子目录下查找 TXT或Java文件,从中搜索所有“对象”字样的行。在D盘中的所有文件中搜索含有“对象”的行。2.解题
- 前段时间spring boot 2.0发布了,与之对应的spring cloud Finchley版本也随之而来了,两者之间的关系和版本对应
- 本文实例讲述了Android开发圆角Button按钮实现过程,分享给大家供大家参考,具体内容如下需求及效果图:实现思路:1、shape实现圆
- 使用RedisTemplate根据前缀获取key列表我们在使用 Redis 的时候,会需要获取以某个字符串开头的所有 key批量获取 key
- 俄罗斯方块Tetris是一款很经典的益智游戏,之前就做了一款桌面版的java俄罗斯方块,这次就尝试着写了一款适用于Android平台的俄罗斯
- 一、项目简述(+需求文档+PPT)功能: 主页显示热销商品;所有商品展示,可进行商品搜索;点 击商品进入商品详情页,显示库存,具有立即购买和
- 今天一直在绞尽脑汁的寻找解决两个字符之间的内容如何输出的问题,刚开始就使用了万能的正则表达式;但是不知哪里的原因自己的数据一直出不来,觉得应
- 以前的左右滑动效果采用自定义scrollview或者linearlayout来实现,recyclerview可以很好的做这个功能,一般的需求