월요일, 5월 27, 2024
HomeLanguageredis cluster java example

redis cluster java example

redis cluster java example

Redis Cluster 에 대한 java example입니다.

LettuceClusterTest.java

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.lettuce.core.RedisURI;
import io.lettuce.core.cluster.RedisClusterClient;
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
import io.lettuce.core.cluster.api.async.RedisAdvancedClusterAsyncCommands;
import io.lettuce.core.support.ConnectionPoolSupport;

public class LettuceClusterTest {
   private static final Logger log = LoggerFactory.getLogger(LettuceClusterTest.class);
         
   private static String lettuceHost = "10.0.0.220:6379,10.0.0.221:6379,10.0.0.222:6379";

   private static RedisClusterClient redisClusterClient;
   private static StatefulRedisClusterConnection<String, Object> redisClusterConnection;
   private static RedisAdvancedClusterAsyncCommands<String, Object> redisClusterAsyncCommands;
   private static GenericObjectPool<StatefulRedisClusterConnection<String, Object>> pool;

   public static boolean isConnectSuccess = false;
   private static int lettuceDefaultTimeout = 3;
   private static int lettuceDefaultExpireTime = 60;
   
   public static void getConnection() {
      log.debug("■ LettuceUtil getConnection start...");

      try {

         if(lettuceHost != null) {
            String [] lettuceHostList = lettuceHost.split(",");
            
          	List<RedisURI> redisURIList = new ArrayList<RedisURI>();
            for(int i = 0 ; i < lettuceHostList.length ; i++) {
               String [] lettuceAdminHostPort = lettuceHostList[i].split(":");
               String host = lettuceAdminHostPort[0];
               int port = Integer.parseInt( lettuceAdminHostPort[1] );
             	RedisURI node = RedisURI.Builder.redis(host).withPort(port).build();
             	redisURIList.add(node);
            }
            
          	redisClusterClient = RedisClusterClient.create(redisURIList);
            
            pool = ConnectionPoolSupport
                           .createGenericObjectPool(() -> redisClusterClient.connect(new SerializedObjectCodec()), new GenericObjectPoolConfig());
            
          	redisClusterConnection = pool.borrowObject();
          	redisClusterAsyncCommands = redisClusterConnection.async();
          	
            log.debug("■ LettuceClientPool created...");
         }
         /**
          * LETTUCE lettuceAdmin Null 일경우
          */
         else {
            log.debug("■ LettuceCache lettuceHost&nbsp;value is Null.");
         }
         
         if (redisClusterClient != null) {
            isConnectSuccess = true;
         }
      } catch (Exception e) {
         log.error("■ Error : " + e.getMessage(), e);
         isConnectSuccess = false;
      }
   }

   /**
    * LETTUCE 연결종료
    */
   public static void closeConnection() {
      log.debug("■ LettuceClient closeConnection start...");

      if (redisClusterClient != null) {
         log.error("■ LettuceClient is null.");
         return;
      }

      try {
         redisClusterConnection.closeAsync();
         pool.close();
           redisClusterClient.shutdown();

         log.debug("■ LettuceClient 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 timeout) {
      if (log.isDebugEnabled()) {
         log.debug("■ LettuceCache Key : " + key);
         log.debug("■ LettuceCache Set obj : " + obj);
         log.debug("■ LettuceCache ExpireTime : " + expireTime);
         log.debug("■ LettuceCache Timeout : " + timeout);
      }

      boolean result = false;

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

      if (!isConnectSuccess) {
         return false;
      }

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

      if (timeout == 0) {
         timeout = lettuceDefaultTimeout;
      }

      Future<String> future = null;

      try {
         future = redisClusterAsyncCommands.set(key, obj);
         redisClusterAsyncCommands.expire(key, expireTime);

         if (future == null) {
            if (log.isDebugEnabled()) {
               log.debug("■ LettuceCache set fail.");
            }

            return false;
         }

         long lettuceTimeout = timeout * 1000;

         String resultFutureString = future.get(lettuceTimeout, TimeUnit.MILLISECONDS);

         if("OK".equals(resultFutureString)) {
            result = true;
         }
         
         if (log.isDebugEnabled()) {
            log.debug("■ LettuceCache set success.");
         }
      } catch (Exception e) {
         log.error("■ Error : " + e.getMessage(), e);

         return false;
      }

      return result;
   }
   
   public static Object getKeyValue(String key) {
      return getKeyValue(key, 0);
   }

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

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

         return null;
      }

      if (timeout == 0) {
         timeout = lettuceDefaultTimeout;
      }

      Future<Object> future = null;

      try {
         future = redisClusterAsyncCommands.get(key);

         if (future == null) {
            if (log.isDebugEnabled()) {
               log.debug("■ LettuceCache get value is null");
            }

            return null;
         }

         long lettuceTimeout = timeout * 1000;

         result = future.get(lettuceTimeout, TimeUnit.MILLISECONDS);

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

         if (future != null) {
            future.cancel(true);
         }

         return null;
      }

      return result;
   }
   
   public static void main(String[] args) {
      getConnection();
      
      String key = "testKey";
      
      setKeyValue(key, "testValue", 60);
      log.info("getKeyValue : " + getKeyValue(key));
   }

}

SerializedObjectCodec.java

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

import io.lettuce.core.codec.RedisCodec;

public class SerializedObjectCodec implements RedisCodec<String, Object> {
    private Charset charset = Charset.forName("UTF-8");

    @Override
    public String decodeKey(ByteBuffer bytes) {
        return charset.decode(bytes).toString();
    }

    @Override
    public Object decodeValue(ByteBuffer bytes) {
        try {
            byte[] array = new byte[bytes.remaining()];
            bytes.get(array);
            ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(array));
            return is.readObject();
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public ByteBuffer encodeKey(String key) {
        return charset.encode(key);
    }

    @Override
    public ByteBuffer encodeValue(Object value) {
        try {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            ObjectOutputStream os = new ObjectOutputStream(bytes);
            os.writeObject(value);
            return ByteBuffer.wrap(bytes.toByteArray());
        } catch (IOException e) {
            return null;
        }
    }
}

 

Previous article
Next article
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