redisへの複数回のアクセスにより、redis接続が切断されるソリューション

2635 ワード

配列ストレージredisリンクを作成し、失効したら自動的に配列を追加します.
 
コードの簡単なコードを添付して、ツッコミを歓迎します
 
package test;

import java.util.Random;

import redis.clients.jedis.Jedis;

public class RedisArrayUtil {
    private static Jedis[] jedisArray;
    private static int jedisArraySize;
    private static String jedisHost;
    private static int jedisPort;
    private static Random random = new Random();

    private RedisArrayUtil(int jedisArraySize, String jedisHost, int jedisPort) {
        this.jedisArraySize = jedisArraySize;
        this.jedisHost = jedisHost;
        this.jedisPort = jedisPort;
        jedisPool();
    }

    @SuppressWarnings("resource")
    public static void jedisPool() {
        jedisArray = new Jedis[jedisArraySize];
        for (int i = 0; i < jedisArraySize; i++) {
            Jedis jedis = new Jedis(jedisHost, jedisPort);
            if (jedis.ping().equals("PONG")) {
                jedisArray[i] = jedis;
            } else {
                jedis = new Jedis(jedisHost, jedisPort);
                jedisArray[i] = jedis;
            }
        }
    }

    public Jedis getConnection() {
        int randomCount;
        Jedis jedis;
        while (true) {
            randomCount = random.nextInt(jedisArraySize - 1);
            jedis = jedisArray[randomCount];
            if (jedis.ping().equals("PONG")) {
                break;
            } else {
                delete(randomCount, jedisArray);
                addJedis();
            }
        }
        return jedis;
    }

    /** @param         */
    public Jedis[] delete(int index, Jedis array[]) {
        Jedis[] jedisArrayNew = new Jedis[array.length - 1];
        for (int i = 0; i < jedisArrayNew.length - 1; i++) {
            if (i < index) {
                jedisArrayNew[i] = array[i];
            } else {
                jedisArrayNew[i] = array[i + 1];
            }
        }
        return jedisArrayNew;
    }

    public void addJedis() {
        @SuppressWarnings("resource")
        Jedis jedis = new Jedis(jedisHost, jedisPort);
        while (true) {
            if (jedis.ping().equals("PONG")) {
                jedisArray[jedisArraySize] = jedis;
                break;
            }
        }
    }

    public static void main(String[] args) {
        RedisArrayUtil redisArrayUtil = new RedisArrayUtil(10, "127.0.0.1",
                6379);
        Jedis jedis = redisArrayUtil.getConnection();
        for (int i = 0; i < 10; i++) {
            System.out.println(redisArrayUtil.getConnection());
        }
        
    }
}