redis - cluster Use Tutorial

redis-cluster tutorial

In the case of billiards projects, I want to write some information about users into the redis cache, because redis is stored in key-value mode. Let's save it. Who's afraid of who?

import com.yuyuka.billiards.service.config.DiamondConfigurtion;
import com.yuyuka.billiards.service.service.lock.JedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import redis.clients.jedis.JedisCluster;

import javax.annotation.Resource;
import java.util.List;

/**
 * Service Center Provides Base Class
 */
@Slf4j
public class AbstractbServiceProvider {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private Registration registration;

    @Autowired
    protected JedisCluster jedisCluster;

    @Resource
    protected DiamondConfigurtion getSuperDiamondAll;

    // Timeout time
    private final int TIMEOUT = 60;

    protected void logInstanceInfo() {
        ServiceInstance instance = serviceInstance();
        log.info("provider service, host = " + instance.getHost()
                + ", service_id = " + instance.getServiceId());
    }


    protected ServiceInstance serviceInstance() {
        List<ServiceInstance> list = discoveryClient.getInstances(registration.getServiceId());
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    protected void lock(String key) {
        JedisLock jedisLock = new JedisLock(jedisCluster, key, TIMEOUT);
        jedisLock.lock();
    }

    protected void unLock(String key) {
        JedisLock jedisLock = new JedisLock(jedisCluster, key, TIMEOUT);
        jedisLock.unlock();
    }

    public int getEndPageSize(Integer start, Integer limit, Integer allSize) {
        return (start + limit) > allSize ? allSize : start + limit - 1;
    }

    /**
     * Verification of longitude and latitude
     * Longitudinal longitude: (?: [0-9] | [1-9] [0-9] | 1 [0-7] [0-9] | 180)\. ([0-9] {6})
     * latitude: (?: [0-9] | [1-8] [0-9] | 90)\. ([0-9] {6})
     *
     * @return
     */
    public boolean checkItude(String longitude, String latitude) {
        String reglo = "((?:[0-9]|[1-9][0-9]|1[0-7][0-9])\\.([0-9]{0,6}))|((?:180)\\.([0]{0,6}))";
        String regla = "((?:[0-9]|[1-8][0-9])\\.([0-9]{0,6}))|((?:90)\\.([0]{0,6}))";
        longitude = longitude.trim();
        latitude = latitude.trim();
        return longitude.matches(reglo) == true ? latitude.matches(regla) : false;
    }
}

Provide a basic class in service, which uses reflection. Other services can inherit this accumulation and improve efficiency.

import com.yuyuka.billiards.service.cache.CacheKeyEnum;
import com.yuyuka.billiards.service.domain.CompetitionStatisticsBasics;
import com.yuyuka.billiards.service.service.AbstractbServiceProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class CompetitionStatisticsServiceProvider extends AbstractbServiceProvider {

    /**
     * Record the user's total field number
     * @param competitionStatisticsBasics
     * @return
     */
    public Boolean addTotalNumbers(CompetitionStatisticsBasics competitionStatisticsBasics) throws Exception {
        try {
            jedisCluster.incrBy(CacheKeyEnum.BILLIARDS_COMPETITION_TOTAL_NUMER.createKey(competitionStatisticsBasics.getUserId1().toString()), 1);
            jedisCluster.incrBy(CacheKeyEnum.BILLIARDS_COMPETITION_TOTAL_NUMER.createKey(competitionStatisticsBasics.getUserId2().toString()), 1);
        }catch (Exception e){
            log.error("Recording User's Total Field Abnormality ",e);
            throw new Exception("redis Insertion exception");
        }
        return true;
    }

    /**
     * Record the total number of users
     * @param competitionStatisticsBasics
     * @return
     * @throws Exception
     */
    public Boolean addTotalNumber(CompetitionStatisticsBasics competitionStatisticsBasics)throws Exception {
        try{
            jedisCluster.incrBy(CacheKeyEnum.BILLIARDS_COMPETITION_TOTAL_GROUPNUMBER.createKey(competitionStatisticsBasics.getUserId1().toString()),1);
            jedisCluster.incrBy(CacheKeyEnum.BILLIARDS_COMPETITION_TOTAL_GROUPNUMBER.createKey(competitionStatisticsBasics.getUserId2().toString()),1);
        }catch(Exception e){
            log.error("Recording the abnormal number of users'general administrations",e);
            throw new Exception("redis Insertion exception");
        }
        return true;
    }

    /**
     * Record the number of wins of users
     */
    public Boolean addWinNumber(CompetitionStatisticsBasics competitionStatisticsBasics) throws Exception {
        try{
            jedisCluster.incrBy(CacheKeyEnum.BILLIARDS_COMPETITION_TOTAL_WINNUMBER.createKey(competitionStatisticsBasics.getUserId1().toString()),1);
            jedisCluster.incrBy(CacheKeyEnum.BILLIARDS_COMPETITION_TOTAL_WINNUMBER.createKey(competitionStatisticsBasics.getUserId2().toString()),1);
        }catch(Exception e){
            log.error("Record abnormal number of user wins",e);
            throw new Exception("redis Insertion exception");
        }
        return true;
    }

    /**
     * Record the total number of user failures
     */
    public Boolean addFailNumber(CompetitionStatisticsBasics competitionStatisticsBasics)throws Exception {
        try{
            jedisCluster.incrBy(CacheKeyEnum.BILLIARDS_COMPETITION_TOTAL_FAILNUMBVER.createKey(competitionStatisticsBasics.getUserId1().toString()),1);
            jedisCluster.incrBy(CacheKeyEnum.BILLIARDS_COMPETITION_TOTAL_FAILNUMBVER.createKey(competitionStatisticsBasics.getUserId2().toString()),1);
        }catch(Exception e){
            log.error("Record the number of user failure fields abnormal",e);
            throw new Exception("redis Insertion exception");
        }
        return true;
    }

    /**
     * Record user cumulative length
     */
    public Boolean addTotalTime(CompetitionStatisticsBasics competitionStatisticsBasics)throws Exception{
        try{
            jedisCluster.incrBy(CacheKeyEnum.BILLIARDS_COMPETITION_TOTAL_TIME.createKey(competitionStatisticsBasics.getUserId1().toString().toString()),1);
            jedisCluster.incrBy(CacheKeyEnum.BILLIARDS_COMPETITION_TOTAL_TIME.createKey(competitionStatisticsBasics.getUserId2().toString()),1);
        }catch(Exception e){
            log.error("Record user cumulative length exceptions",e);
            throw new Exception("redis Insertion exception");
        }
        return true;
    }
    public Boolean addKoUsers(CompetitionStatisticsBasics competitionStatisticsBasics)throws Exception {
        try{
            jedisCluster.incrBy(CacheKeyEnum.BILLIARDS_COMPETITION_KO_USERS.createKey(competitionStatisticsBasics.getUserId1().toString()),1);
            jedisCluster.incrBy(CacheKeyEnum.BILLIARDS_COMPETITION_KO_USERS.createKey(competitionStatisticsBasics.getUserId2().toString()),1);
        }catch(Exception e){
            log.error("Record each other ko Two opponents",e);
            throw new Exception("redis Insertion exception");
        }
        return true;
    }
}

I'll talk about this incrBy method. The source code is as follows.

  @Override
  public Long incrBy(final String key, final long integer) {
    return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
      @Override
      public Long execute(Jedis connection) {
        return connection.incrBy(key, integer);
      }
    }.run(key);
  }
  @Override
    public long incrBy(String key, long incr) throws Exception {
        ShardedJedis shardedJedis = null;
        boolean broken = false;
        try {
            shardedJedis = shardedJedisPool.getResource();
            boolean isExist = shardedJedis.exists(key);
            if (!isExist) {
                shardedJedis.set(key, 0 + "");
            }
            long result = shardedJedis.incrBy(key, incr);
            return result;
        } catch (JedisException e) {
            broken = handleJedisException(e);
            throw e;
        } finally {
            closeResourse(shardedJedis, broken);
        }
    }
	
}

The Redis Incrby command adds the number stored in the key to the specified incremental value. If the key does not exist, the value of the key is initialized to zero before executing the INCRBY command.
Have you noticed Competition Statistics Basics and Cache Key Enum? Show the following two figure codes:

import com.yuyuka.billiards.api.type.CompetitionTypeEnum;
import lombok.Data;

import java.math.BigDecimal;
import java.util.Date;

@Data
public class CompetitionStatisticsBasics implements java.io.Serializable{
    // Match type
    public CompetitionTypeEnum competitionTypeEnum;
    // start time
    public  Date beginDate;
    // End time
    public Date endDate;
    // Participant 1
    public BigDecimal userId1;
    // Participant 2
    public BigDecimal userId2;
    // Participant 1 score
    public Integer userId1Point;
    //Participants scored 2 points
    public Integer userid2Point;
}

The base class defines some instance objects and simplifies the code by using @Data. Its purpose is to eliminate the flow of get (), set (), and toStirng ().

  // User Competition Statistics
    BILLIARDS_COMPETITION_TOTAL_NUMER("com:yuyuka:billiards:cache:competition:total:number","Total number of user games"),
    BILLIARDS_COMPETITION_TOTAL_WINNUMBER("com:yuyuka:billiards:cache:competition:total:winnumber","Total number of user victories"),
    BILLIARDS_COMPETITION_TOTAL_GROUPNUMBER("com:yuyuka:billiards:cache:competition:total:groupynumber","Number of General Administration of User Competition"),
    BILLIARDS_COMPETITION_TOTAL_FAILNUMBVER("com:yuyuka:billiaeds:cache:competition:total:failnumber","Total number of user failures"),
    BILLIARDS_COMPETITION_TOTAL_TIME("com:yuyuka:billiaeds:cache:competition:total:time","User cumulative length"),
    BILLIARDS_COMPETITION_KO_USERS("com:yuyuka:billiaeds:cache:competition:ko:users","Two Users Fight");

enum enumeration defines the possible values of a variable.

Keywords: Redis Java Lombok Jedis

Added by markanite on Tue, 01 Oct 2019 02:22:21 +0300