Table of Contents
1 The concept of redis master-slave replication
2 Why master-slave replication is needed
3 Master-slave replication configuration and principle
4 Use Lettuce to execute commands in master-slave mode
1. In the pom.xml file of the project, introduce the relevant Jar package dependencies of Redis under Spring Boot
2. In the resources directory of the project, in the application.yml file Add lettuce configuration parameters
3. Add Redisson configuration parameter reading class RedisConfig
4. Build Spring Boot startup class RedisApplication
5. Write tests Class RedisTest
6. View the running results on Redis
Home Database Redis How Java uses Lettuce client to execute commands in Redis master-slave mode

How Java uses Lettuce client to execute commands in Redis master-slave mode

May 31, 2023 pm 09:05 PM
java redis lettuce

1 The concept of redis master-slave replication

In a multi-machine environment, a redis service receives write commands and copies them to one or more redis when its own data and status change. This mode is called master-slave replication. Through the command slaveof, one Redis server can copy the data and status of another Redis server in Redis. We call the main server master and the slave server slave.

Master-slave replication ensures that data will be replicated when the network is abnormal and the network is disconnected. When the network is normal, the master will keep updating the slave by sending commands. The updates include client writes, key expiration or eviction and other network abnormalities. The master is disconnected from the slave for a period of time. The slave will try to partially reconnect after reconnecting to the master. Synchronize, reacquire commands lost during disconnection. When partial resynchronization cannot be performed, full resynchronization will be performed.

2 Why master-slave replication is needed

In order to ensure that data is not lost, the persistence function is sometimes used. But this will increase disk IO operations. Using master-slave replication technology can replace persistence and reduce IO operations, thereby reducing latency and improving performance.

In the master-slave mode, the master is responsible for writing and the slave is responsible for reading. Although master-slave synchronization may cause data inconsistency, it can improve the throughput of read operations. The master-slave model avoids redis single point risk. Improve system availability through replicas. If the master node fails, the slave node elects a new node as the master node to ensure system availability.

3 Master-slave replication configuration and principle

Master-slave replication can be divided into three stages: initialization, synchronization, and command propagation.

After the server executes the slaveof command, the slave server establishes a socket connection with the master server and completes the initialization. If the main server is normal, after establishing the connection, it will perform heartbeat detection through the ping command and return a response. When a failure occurs and no response is received, the slave node will retry to connect to the master node. If the master sets authentication information, it will then check whether the authentication data is correct. If authentication fails, an error will be reported.

After the initialization is completed, when the master receives the data synchronization instruction from the slave, it needs to determine whether to perform full synchronization or partial synchronization according to the situation.

After the synchronization is completed, the master server and the slave server confirm each other's online status through heartbeat detection for command transmission. The slave also sends the offset of its own copy buffer to the master. Based on these requests, the master will determine whether the newly generated commands need to be synchronized to the slave. The slave executes the synchronization command after receiving it, and finally synchronizes with the master.

4 Use Lettuce to execute commands in master-slave mode

Jedis, Redission and Lettuce are common Java Redis clients. Lettuce will be used to demonstrate the read-write separation command execution in master-slave mode.

        <dependency>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
Copy after login

The following is supplemented by

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();
    }
}
Copy after login

: Lettuce configuration and use of Redis client (based on Spring Boot 2.x)

Development environment: using Intellij IDEA Maven Spring Boot 2.x JDK 8

Spring Boot Starting from version 2.0, the default Redis client Jedis will be replaced by Lettuce. The configuration and use of Lettuce is described below.

1. In the pom.xml file of the project, introduce the relevant Jar package dependencies of Redis under Spring Boot

    <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>
Copy after login

2. In the resources directory of the project, in the application.yml file Add lettuce configuration parameters

#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    #连接超时时间(毫秒)
Copy after login

3. Add Redisson configuration parameter reading class 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;
    }
}
Copy after login

4. Build Spring Boot startup class 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);
    }
}
Copy after login

5. Write tests Class 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("hash2", "name1", "lms1");
        redisTemplate.opsForHash().put("hash2", "name2", "lms2");
        redisTemplate.opsForHash().put("hash2", "name3", "lms3");
        System.out.println(redisTemplate.opsForValue().get("test:set"));
        System.out.println(redisTemplate.opsForHash().get("hash2", "name1"));
    }
}
Copy after login

6. View the running results on Redis

The above is the detailed content of How Java uses Lettuce client to execute commands in Redis master-slave mode. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Composer Expertise: What Makes Someone Skilled Composer Expertise: What Makes Someone Skilled Apr 11, 2025 pm 12:41 PM

To become proficient when using Composer, you need to master the following skills: 1. Proficient in using composer.json and composer.lock files, 2. Understand how Composer works, 3. Master Composer's command line tools, 4. Understand basic and advanced usage, 5. Familiar with common errors and debugging techniques, 6. Optimize usage and follow best practices.

See all articles