JedisPool的配置参数很大程度上依赖于实际应用需求、软硬件能力,JedisPool的配置参数大部分是由JedisPoolConfig的对应项来赋值的。

 

maxActive:控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态就成exhausted了,在JedisPoolConfig

maxIdle:控制一个pool最多有多少个状态为idle的jedis实例;

whenExhaustedAction:表示当pool中的jedis实例都被allocated完时,pool要采取的操作;默认有三种WHEN_EXHAUSTED_FAIL(表示无jedis实例时,直接抛出NoSuchElementException)、WHEN_EXHAUSTED_BLOCK(则表示阻塞住,或者达到maxWait时抛出JedisConnectionException)、WHEN_EXHAUSTED_GROW(则表示新建一个jedis实例,也就说设置的maxActive无用);

maxWait:表示当borrow一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;

testOnBorrow:在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的;

testOnReturn:在return给pool时,是否提前进行validate操作;

testWhileIdle:如果为true,表示有一个idle object evitor线程对idle object进行扫描,如果validate失败,此object会被从pool中drop掉;这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义;

timeBetweenEvictionRunsMillis:表示idle object evitor两次扫描之间要sleep的毫秒数;

numTestsPerEvictionRun:表示idle object evitor每次扫描的最多的对象数;

minEvictableIdleTimeMillis:表示一个对象至少停留在idle状态的最短时间,然后才能被idle object evitor扫描并驱逐;这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义;

softMinEvictableIdleTimeMillis:在minEvictableIdleTimeMillis基础上,加入了至少minIdle个对象已经在pool里面了。如果为-1,evicted不会根据idle time驱逐任何对象。如果minEvictableIdleTimeMillis>0,则此项设置无意义,且只有在timeBetweenEvictionRunsMillis大于0时才有意义;

lifo:borrowObject返回对象时,是采用DEFAULT_LIFO(last in first out,即类似cache的最频繁使用队列),如果为False,则表示FIFO队列;

 

其中JedisPoolConfig对一些参数的默认设置如下:

testWhileIdle=true
 minEvictableIdleTimeMills=60000
 timeBetweenEvictionRunsMillis=30000
 numTestsPerEvictionRun=-1

package com.ecbt.util.redis;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;

import com.ecbt.util.CoreUtils;

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

/**
 * Redis的工具类
 * 
 * @ClassName: RedisUtil
 * @author sunbaojin
 * @date 2017-11-06 15:07:55
 */
public final class RedisUtil {
    public static InputStream in = null;
    public static Properties prop = new Properties();

    /**
     * 读取配置文件
     * 
     * @Title: readConfigInfo
     * @date 2017-12-18 10:47:05 void
     * @author sunbaojin
     */
    private static void readConfigInfo() {

        try {
            String userHome = System.getenv("user_home");
            if (CoreUtils.notNull(userHome)) {
                // 获取配置文件路径信息
                in = new FileInputStream(userHome + "/fta-redis.properties");
                prop.load(in);
                RedisUtil.REDIS_URL = prop.getProperty("redis.url");
                RedisUtil.REDIS_PORT = Integer.parseInt(prop.getProperty("redis.port"));
                RedisUtil.REDIS_PASSWORD = prop.getProperty("redis.password");
                RedisUtil.REDIS_MAX_IDLE = Integer.parseInt(prop.getProperty("redis.maxIdle"));
                RedisUtil.REDIS_MAX_WAIT = Integer.parseInt(prop.getProperty("redis.maxWait"));
                RedisUtil.REDIS_TIMEOUT = Integer.parseInt(prop.getProperty("redis.timeout"));
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Redis服务器IP
     */
    public static String REDIS_URL = "192.168.40.22";

    /**
     * Redis的端口号
     */
    public static int REDIS_PORT = 6379;

    /**
     * 访问密码
     */
    public static String REDIS_PASSWORD = "admin";

    /**
     * 可用连接实例的最大数目,默认值为8;
     * 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
     **/
    public static int REDIS_MAX_ACTIVE = 1024;

    /**
     * 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
     */
    public static int REDIS_MAX_IDLE = 200;

    /**
     * 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
     */
    public static int REDIS_MAX_WAIT = 10000;

    /**
     * 超时时间
     */
    public static int REDIS_TIMEOUT = 100000;

    /**
     * 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
     */
    private static boolean REDIS_TEST_ON_BORROW = true;

    /**
     * 实例
     */
    private static JedisPool jedisPool = null;

    /**
     * 初始化Redis连接池
     */
    static {
        try {
            readConfigInfo();
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(REDIS_MAX_ACTIVE);
            config.setMaxIdle(REDIS_MAX_IDLE);
            config.setMaxWaitMillis(REDIS_MAX_WAIT);
            config.setTestOnBorrow(REDIS_TEST_ON_BORROW);
            // jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, REDIS_PASSWORD);
            jedisPool = new JedisPool(config, REDIS_URL, REDIS_PORT, REDIS_TIMEOUT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Jedis实例
     * 
     * @return
     */
    private synchronized static Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 释放jedis资源
     * 
     * @param jedis
     */
    private static void close(final Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    /**
     * Set the string value as value of the key. The string can't be longer than
     * 1073741824 bytes (1 GB).
     * 
     * @Title: addJsonData
     * @date 2017-11-07 08:59:46
     * @param jsonDataKey
     *            json数据的key
     * @param jsonData
     *            json数据
     * @author sunbaojin
     */
    public static void addJsonData(String jsonDataKey, String jsonData) {
        // 向jedis存放数据
        if (jsonData != null) {
            Jedis jedis = RedisUtil.getJedis();
            try {
                // 开始前,先移除所有的内容
                jedis.del(jsonDataKey);
                jedis.set(jsonDataKey, jsonData);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 关闭单个资源信息,使用完毕就释放这个资源
                close(jedis);
            }
        }
    }

    /**
     * Set a timeout on the specified key. After the timeout the key will be
     * automatically deleted by the server. A key with an associated timeout is said
     * to be volatile in Redis terminology.
     * 
     * @Title: expire
     * @date 2017-12-25 13:36:36
     * @param redisKey
     *            redis中的key
     * @param seconds
     *            超时的时间(以秒为单位) void
     * @author sunbaojin
     */
    public static void expire(String redisKey, int seconds) {
        // 向jedis存放数据
        if (redisKey != null) {
            Jedis jedis = RedisUtil.getJedis();
            try {
                // 如果存在,设置超时时间
                if (jedis.exists(redisKey)) {
                    // 开始前,先移除所有的内容
                    jedis.expire(redisKey, seconds);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 关闭单个资源信息,使用完毕就释放这个资源
                close(jedis);
            }
        }
    }

    /**
     * Return all the fields in a hash.
     * 
     * @Title: hkeys
     * @date 2017-12-25 13:56:21
     * @param redisKey
     *            redis中的key
     * @return Set<String> All the fields names contained into a hash.
     * @author sunbaojin
     */
    public static Set<String> hkeys(String redisKey) {
        Set<String> hkeySet = null;
        Jedis jedis = RedisUtil.getJedis();
        try {
            hkeySet = jedis.hkeys(redisKey);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭单个资源信息,使用完毕就释放这个资源
            close(jedis);
        }
        return hkeySet;
    }

    /**
     * 根据key删除redis中的数据
     * 
     * @Title: del
     * @date 2017-12-25 13:48:40
     * @param redisKey
     *            redis中的key void
     * @author sunbaojin
     */
    public static void del(String redisKey) {
        // 向jedis存放数据
        if (redisKey != null) {
            Jedis jedis = RedisUtil.getJedis();
            try {
                jedis.del(redisKey);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 关闭单个资源信息,使用完毕就释放这个资源
                close(jedis);
            }
        }
    }

    /**
     * Set the specified hash field to the specified value. If key does not exist, a
     * new key holding a hash is created.
     * 
     * @Title: hset
     * @date 2017-12-25 13:51:26
     * @param key
     *            redis的key
     * @param field
     *            字段
     * @param value
     *            字段值 void
     * @author sunbaojin
     */
    public static void hset(String key, String field, String value) {
        Jedis jedis = RedisUtil.getJedis();
        try {
            jedis.hset(key, field, value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭单个资源信息,使用完毕就释放这个资源
            close(jedis);
        }
    }

    /**
     * Returns all the keys matching the glob-style pattern as space separated
     * strings. For example if you have in the database the keys "foo" and "foobar"
     * the command "KEYS foo*" will return "foo foobar".
     * 
     * @Title: redisKeys
     * @date 2017-12-25 13:44:54
     * @param pattern
     * @return Set<String>
     * @author sunbaojin
     */
    public static Set<String> keys(String pattern) {
        Set<String> keySet = null;
        Jedis jedis = RedisUtil.getJedis();
        try {
            keySet = jedis.keys(pattern);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭单个资源信息,使用完毕就释放这个资源
            close(jedis);
        }
        return keySet;
    }

    /**
     * Test if the specified key exists. The command returns "1" if the key exists,
     * otherwise "0" is returned. Note that even keys set with an empty string as
     * value will return "1". Time complexity: O(1)
     * 
     * @Title: checkRedisKeyExists
     * @date 2017-12-25 13:41:11
     * @param redisKey
     *            redis中的key
     * @return Boolean
     * @author sunbaojin
     */
    public static Boolean exists(String redisKey) {
        Boolean isExists = false;
        // 向jedis存放数据
        if (redisKey != null) {
            Jedis jedis = RedisUtil.getJedis();
            try {
                // 判断redis中的key是否存在
                isExists = jedis.exists(redisKey);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 关闭单个资源信息,使用完毕就释放这个资源
                close(jedis);
            }
        }
        return isExists;
    }

    /**
     * Get the value of the specified key. If the key does not exist null is
     * returned. If the value stored at key is not a string an error is returned
     * because GET can only handle string values.
     * 
     * @Title: getJsonData
     * @date 2017-11-07 09:01:02
     * @param jsonDataKey
     *            json对象的key
     * @return String json对象
     * @author sunbaojin
     */
    public static String getJsonData(String jsonDataKey) {
        Jedis jedis = RedisUtil.getJedis();
        String jsonData = null;
        try {
            jsonData = jedis.get(jsonDataKey);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(jedis);
        }
        return jsonData;
    }

    /**
     * 加载所有的字典项信息
     * 
     * @Title: loadAllDictData
     * @date 2017-11-22 13:47:27 void
     * @author sunbaojin
     */
    public static void loadAllDictData() {
        // 加载所有的字典项
        SysDictTool.readAndWriteDictFiles();
    }

    public static void main(String[] args) {
        String userHome = System.getenv("user_home");
        System.out.println(userHome);
        Jedis jedis = RedisUtil.getJedis();
        // jedis.flushAll();
        // 查看服务是否运行
        System.out.println("服务正在运行: " + jedis.ping());
        try {
            Set<String> dictSubList = jedis.keys("*");
            for (String string : dictSubList) {
                System.out.println(string);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            RedisUtil.close(jedis);
        }
        System.out.println(RedisUtil.getJedis().get("FTA_SYS0000021"));

    }

}