Redis接続プールツールクラスとプロファイルのロードとテスト


srcでpropertiesファイルを作成します.内容は次のとおりです.
# IP
host=localhost
#    
port=6379
#      
maxTotal=50
#      
maxIdle=20

接続プールツールクラス:
package cd.zf.utils;

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

import java.util.ResourceBundle;

    /*
              
                 jedis
            config.properties
     */

public class JedisUtils {
    //       
    private static JedisPool pool;
    //      
    static {
        /**
         * ResourceBundle  java.util.ResourceBundle 
         *          properties  
         *        new,     --->ResourceBundle.getBundle("config");
         *      getBundle(String baseName)   baseName       ,     config
         *      getBundle(String baseName)        getString(String key)  
         *      getString(String key)            ,key      key   
         *              String  ,       -->Integer
         */
        ResourceBundle config = ResourceBundle.getBundle("config");
        //  ip
        String host = config.getString("host");
        //     
        int port = Integer.parseInt(config.getString("port"));
        //       
        int maxTotal = Integer.parseInt(config.getString("maxTotal"));
        //         
        int maxIdle = Integer.parseInt(config.getString("maxIdle"));
        //          
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        //       
        jedisPoolConfig.setMaxTotal(maxTotal);
        //         
        jedisPoolConfig.setMaxIdle(maxIdle);
        //                    、IP       
        pool = new JedisPool(jedisPoolConfig, host, port);
    }
    //    ,       
    public static Jedis getJedis(){
        return pool.getResource();
    }

    //    
    //      
    public static void close(Jedis jedis){
        if (jedis!=null)
            jedis.close();
    }
    //       
    public static void close(JedisPool pool){
        if (pool!=null)
            pool.close();
    }
}


テスト:
package cd.zf.redis;

import cd.zf.utils.JedisUtils;
import org.junit.Test;
import redis.clients.jedis.Jedis;

public class JedisUtilsTest {
    @Test
    public void test(){
        Jedis jedis = JedisUtils.getJedis();
        jedis.set("username","tom");
        String username = jedis.get("username");
        System.out.println(username);
        JedisUtils.close(jedis);
    }
}