编程知识 cdmana.com

Redis sentry mechanism

About redis It's divided into sections

advantage : Realize the expansion of memory data .
shortcoming : If redis There is a problem with a node in the shard , Then the whole redis There will be some problems in the user access of fragmentation mechanism , Directly affect the use of users .
Solution : Realization redis High availability .

To configure redis Master-slave structure

Strategy Division :1 Lord 2 from 6379 Lord 6380/6381 from
1. Copy the partitioned directory Renamed as sentinel
image.png
2. restart redis The server
image.png
3. Check redis The master-slave state of the node
image.png
4. Realize the master-slave mount
image.png
5. Check host status
image.png

How the sentry works

image.png
Principle that :
1. To configure redis The structure of master-slave .
2. When sentinel service starts , Will monitor the current host , At the same time, get the details of the host ( The structure of master-slave ).
3. When sentinel Liu Yong heartbeat detection mechanism (PING-PANG) continuity 3 If no feedback is received from the host, the host will be judged to be down .
4. When the sentry found out that the main engine was down , The election mechanism will be opened , Choose one of the current slaves Redis As a mainframe .
5. Take the rest redis The node is set as the slave of the new host .

Edit sentinel profile

1. Copy profile
cp sentinel.conf sentinel/
2. Change protection mode
image.png
3. Turn on background operation
image.png
4. Set up sentinel surveillance
Among them 1 The number of votes in effect , There is only one sentry at present, so write 1
image.png
5. Modify downtime
image.png
6. When the election failed
explain : If the election does not end beyond the specified time , Re election
image.png
7. Start sentinel service
image.png

Redis Sentinel high availability implementation

testing procedure :
1. Check the status of the host
2. take redis The primary server is down and waiting 10 second , Then check whether the slave is selected as the new host .
image.png
3. restart 6379 The server , Check whether it becomes the slave of the new host
image.png

Sentinel entry case

/**
     *  test Redis sentry 
     */
    @Test
    public void testSentinel(){
        Set<String> set = new HashSet<>();
        //1. Pass the sentinel configuration information 
        set.add("192.168.126.129:26379");
        JedisSentinelPool sentinelPool =
                new JedisSentinelPool("mymaster",set);
        Jedis jedis = sentinelPool.getResource();
        jedis.set("aa"," sentinel test ");
        System.out.println(jedis.get("aa"));
    }

SpringBoot Integrate Redis sentry

edit pro The configuration file

#  To configure redis Single server 
redis.host=192.168.126.129
redis.port=6379

#  To configure redis Fragmentation mechanism 
redis.nodes=192.168.126.129:6379,192.168.126.129:6380,192.168.126.129:6381

#  Configure sentinel nodes 
redis.sentinel=192.168.126.129:26379

edit redis Configuration class

@Configuration
@PropertySource("classpath:/properties/redis.properties")
public class JedisConfig {

    @Value("${redis.sentinel}")
    private String sentinel;        // For the time being, there's only one 

    @Bean
    public JedisSentinelPool jedisSentinelPool(){

        Set<String> sentinels = new HashSet<>();
        sentinels.add(sentinel);
        return new JedisSentinelPool("mymaster",sentinels);
    }
  }

modify CacheAOP The injection term in

package com.jt.aop;

import com.jt.anno.CacheFind;
import com.jt.config.JedisConfig;
import com.jt.util.ObjectMapperUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.ShardedJedis;

import java.lang.reflect.Method;
import java.util.Arrays;

@Aspect     // I am a AOP Section class 
@Component  // Give the class to spring Container management 
public class CacheAOP {

    @Autowired
    //private Jedis jedis;      // A single redis
    //private ShardedJedis jedis; // Fragmentation mechanism 
    private JedisSentinelPool jedisSentinelPool;

    /**
     *  section  =  The breakthrough point  +  Notification method 
     *         Annotations associated  +  Surrounding the notification    Control whether the target method is implemented 
     *
     *   difficulty :
     *      1. How to get annotation objects 
     *      2. Dynamic generation key  prekey +  User parameter array 
     *      3. How to get the return value type of a method 
     */
    @Around("@annotation(cacheFind)")  // Parameter transfer variable transfer 
    //@Around("@annotation(com.jt.anno.CacheFind)")
    public Object around(ProceedingJoinPoint joinPoint,CacheFind cacheFind){
        // Get... From the pool jedis object 
        Jedis jedis = jedisSentinelPool.getResource();
        Object result = null;
        try {
            //1. Splicing redis Storing data key
            Object[] args = joinPoint.getArgs();
            String key = cacheFind.preKey() +"::" + Arrays.toString(args);

            //2.  Inquire about redis  Then judge whether there is data 
            if(jedis.exists(key)){
                //redis There's a record in , There is no need to execute the target method 
                String json = jedis.get(key);
                // Get the return value type of the method dynamically     Look up    Shape down 
                MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
                Class returnType = methodSignature.getReturnType();
                result = ObjectMapperUtil.toObj(json,returnType);
                System.out.println("AOP Inquire about redis cache ");
            }else{
                // Indicates that the data does not exist , Need to query database 
                result = joinPoint.proceed();  // Implementation target method and notification 
                // Save the query results to redis In the middle 
                String json = ObjectMapperUtil.toJSON(result);
                // Determine whether the data needs a timeout 
                if(cacheFind.seconds()>0){
                    jedis.setex(key,cacheFind.seconds(),json);
                }else {
                    jedis.set(key, json);
                }
                System.out.println("aop Execute target method query database ");
            }

        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        jedis.close();  // Remember to close the completed link .
        return result;
    }

}

版权声明
本文为[Xiaofei]所创,转载请带上原文链接,感谢

Scroll to Top