java redis pool

ขั้นแรกไปโหลด jedis-2.1.0.jar และ common-pool-1.6.jar มาก่อน และสร้างโฟลเดอ lib ขึ้นมา นำไฟล์ทั้ง 2 ไปวาง
และคลิกขวา > Build Path > Add to Class path
จากนั้นสามารถนำโค้ดนี้ไปใช้งานได้เลย

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

public class Redis {
    private static Jedis redis = null;
    private static int expire = 10;//10 seconds
    private static String host = "127.0.0.1";
    private static int port = 6379;
    public static void testConnect(){
       
        try
        {  
            JedisPoolConfig poolConfig = new JedisPoolConfig();
            // Maximum active connections to Redis instance
            poolConfig.setMaxActive(10);
            // Tests whether connection is dead when connection
            // retrieval method is called
            poolConfig.setTestOnBorrow(true);
            /* Some extra configuration */
            // Tests whether connection is dead when returning a
            // connection to the pool
            poolConfig.setTestOnReturn(true);
            // Number of connections to Redis that just sit there
            // and do nothing
            poolConfig.setMaxIdle(5);
            // Minimum number of idle connections to Redis
            // These can be seen as always open and ready to serve
            poolConfig.setMinIdle(1);
            // Tests whether connections are dead during idle periods
            poolConfig.setTestWhileIdle(true);
            // Maximum number of connections to test in each idle check
            poolConfig.setNumTestsPerEvictionRun(10);
            // Idle connection checking period
            poolConfig.setTimeBetweenEvictionRunsMillis(60000);
            // Create the jedisPool

            //redis = new Jedis("10.224.205.24",6386);
            //redis = new Jedis("127.0.0.1",6379);
            JedisPool pool = new JedisPool(poolConfig,host,port);

            redis = pool.getResource();

            redis.set("foo", "bar2");
            redis.expire("foo", expire);
            String value = redis.get("foo");
         
            System.out.println(value);
            //check whether server is running or not
   
        }catch (JedisConnectionException e)
        {
            System.out.println(e.getMessage());
        }
    }

}

Related posts:

This entry was posted in java. Bookmark the permalink.