수요일, 5월 22, 2024
HomeLanguageRedis sentinel java example

Redis sentinel java example

Redis sentinel java example

Redis Sentinel – HAProxy을 이용한 Client 통신에 대한 java example입니다.

Master(5000 port) 는 set(write) 용도

Slave(5001 port)는 get(read) 용도

JedisSentinalTest.java

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.time.Duration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisSentinalTest {
   private static final Logger log = LoggerFactory.getLogger(JedisSentinalTest.class);
   
   private static JedisPoolConfig jedisPoolConfig = buildPoolConfig();
   private static JedisPool jedisMasterPool;
   private static Jedis jedisMasterClient;
   private static JedisPool jedisSlavePool;
   private static Jedis jedisSlaveClient;
   
   public static boolean isMasterConnectSuccess = false;
   public static boolean isSlaveConnectSuccess = false;

   private static String redisHost = "lcoalhost";
   private static int redisMasterPort = 5000;
   private static int redisSlavePort = 5001;
   private static int redisDefaultExpireTime = 60;
   
   private static JedisPoolConfig buildPoolConfig() {
       final JedisPoolConfig poolConfig = new JedisPoolConfig();
       
       poolConfig.setMaxTotal(4096);
       poolConfig.setMaxIdle(500);
       poolConfig.setMinIdle(200);
       poolConfig.setTestOnBorrow(true);
       poolConfig.setTestOnReturn(true);
       poolConfig.setTestWhileIdle(true);
       poolConfig.setMinEvictableIdleTimeMillis(Duration.ofSeconds(60).toMillis());
       poolConfig.setTimeBetweenEvictionRunsMillis(Duration.ofSeconds(30).toMillis());
       poolConfig.setNumTestsPerEvictionRun(3);
       poolConfig.setBlockWhenExhausted(true);
       
       return poolConfig;
   }
   
   public static void getMasterConnection() {
      log.info("■ RedisUtil getConnection start...");

      try {
         /**
          * jedisPool
          */
         jedisMasterPool = new JedisPool(jedisPoolConfig, redisHost, redisMasterPort, 60000, "password");
         jedisMasterClient = jedisMasterPool.getResource();
         
         log.info("■ RedisClientPool created...");

         if (jedisMasterPool != null) {
            isMasterConnectSuccess = true;
         }
      } catch (Exception e) {
         log.error("■ 에러 : " + e.getMessage(), e);
         isMasterConnectSuccess = false;
      }
   }
   
   public static void getSlaveConnection() {
      log.info("■ RedisUtil getConnection start...");

      try {
         /**
          * jedisPool
          */
         jedisSlavePool = new JedisPool(jedisPoolConfig, redisHost, redisSlavePort, 60000, "password");
         jedisSlaveClient = jedisSlavePool.getResource();
         
         log.info("■ RedisClientPool created...");

         if (jedisSlavePool != null) {
            isSlaveConnectSuccess = true;
         }
      } catch (Exception e) {
         log.error("■ 에러 : " + e.getMessage(), e);
         isSlaveConnectSuccess = false;
      }
   }

   /**
    * Master 연결종료
    *
    * @throws Exception
    */
   public static void closeMasterConnection() {
      log.info("■ RedisClientPool closeConnection start...");

      if (jedisMasterPool == null) {
         log.error("■ RedisClientPool is null.");
         return;
      }

      try {
         jedisMasterClient.close();
         jedisMasterPool.destroy();

         log.error("■ RedisMasterClientPool closed...");
      } catch (Exception e) {
         log.error("■ 에러 : " + e.getMessage(), e);
      }
   }


   /**
    * Slave 연결종료
    *
    * @throws Exception
    */
   public static void closeSlaveConnection() {
      log.info("■ RedisClientPool closeConnection start...");

      if (jedisSlavePool == null) {
         log.error("■ RedisClientPool is null.");
         return;
      }

      try {
         jedisSlaveClient.close();
         jedisSlavePool.destroy();

         log.error("■ RedisSlaveClientPool closed...");
      } catch (Exception e) {
         log.error("■ 에러 : " + e.getMessage(), e);
      }
   }
   
   public static boolean setKeyValue(String key, Object obj, int expireTime) {
      return setKeyValue(key, obj, expireTime, 0);
   }

   /**
    * Key-Value Item 저장
    */
   public static boolean setKeyValue(String key, Object obj, int expireTime, int selectDb) {
      boolean result = true;

      if (obj == null) {
         if (log.isDebugEnabled()) {
            log.debug("■■ RedisCache set value is null.");
         }
         return false;
      }
      
      if (!isMasterConnectSuccess) {
         return false;
      }

      if (expireTime == 0) {
         expireTime = redisDefaultExpireTime;
      }

      String statusCodeReply = null;

      try {
         byte[] svalue = serialize(obj);
         jedisMasterClient.select(selectDb);
         statusCodeReply = jedisMasterClient.setex(key.getBytes(), expireTime, svalue);
         if (statusCodeReply == null) {
            if (log.isDebugEnabled()) {
               log.debug("■ RedisCache set fail.");
            }

            return false;
         }
         
         if (log.isDebugEnabled()) {
            log.debug("■ RedisCache set success.");
         }
      } catch (Exception e) {
         log.error("■ Error : " + e.getMessage(), e);

         return false;
      }

      return result;
   }

   /**
    * Key-Value Item 조회
    */
   public static Object getKeyValue(String key) {
      return getKeyValue(key, 0);
   }

   /**
    * Key-Value Item 조회
    */
   public static Object getKeyValue(String key, int selectDb) {
      Object result = null;

      if (!isSlaveConnectSuccess) {
         if (log.isDebugEnabled()) {
            log.debug("■ RedisCache Connection value is false.");
         }

         return null;
      }

      try {
         jedisSlaveClient.select(selectDb);
         byte [] tmp = jedisSlaveClient.get(key.getBytes());

         if (tmp == null) {
            if (log.isDebugEnabled()) {
               log.debug("■ RedisCache get key[ " + key  + " ] value is null");
            }

            return null;
         }
         
         result = deserialize(tmp);

         if (result == null) {
            if (log.isDebugEnabled()) {
               log.debug("■ RedisCache get key[ " + key  + " ] value is null");
            }

            return null;
         }
         
         if (log.isDebugEnabled()) {
            log.debug("■ RedisCache Result : " + result);
         }
      } catch (Exception e) {
         log.error("■ Error : " + e.getMessage(), e);

         return null;
      }

      return result;
   }
   
   public static byte[] serialize(Object value) {
      if (value == null) {
         throw new NullPointerException("Can't serialize null");
      }
      byte[] rv = null;
      ByteArrayOutputStream bos = null;
      ObjectOutputStream os = null;
      try {
         bos = new ByteArrayOutputStream();
         os = new ObjectOutputStream(bos);
         os.writeObject(value);
         rv = bos.toByteArray();
      } catch (Exception e) {
         throw new RuntimeException("Object can't be serialized", e);
      } finally {
         close(os);
         close(bos);
      }
      return rv;
   }

   public static Object deserialize(byte[] in) {
      return deserialize(in, new Object());
   }

   @SuppressWarnings("unchecked")
   public static <T> T deserialize(byte[] in, Object requiredType) {
      Object rv = null;
      ByteArrayInputStream bis = null;
      ObjectInputStream is = null;
      try {
         if (in != null) {
            bis = new ByteArrayInputStream(in);
            is = new ObjectInputStream(bis);
            rv = is.readObject();
         }
      } catch (Exception e) {
         throw new RuntimeException("Object can't be deserialized", e);
      } finally {
         close(is);
         close(bis);
      }
      return (T) rv;
   }

   private static void close(Closeable closeable) {
      if (closeable != null)
         try {
            closeable.close();
         } catch (IOException e) {
            throw new RuntimeException("close stream error");
         }
   }
   
   public static void main(String[] args) {
      getMasterConnection(); //Redis Sentinal Master(5000 port) Connection 
      getSlaveConnection(); //Redis Sentinal Salve(5001 port) Connection
      
      String key = "testKey";
      
      setKeyValue(key, "testValue", 60);
      log.info("getKeyValue : " + getKeyValue(key));
   }

}

 

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Time limit exceeded. Please complete the captcha once again.

Most Popular