AnimeCharacterPack1







redis作为缓存型数据库,越来越受到大家的欢迎,这里简单介绍一下java如何操作redis。


1、java连接redis

java通过需要jedis的jar包获取Jedis连接。  

jedis-2.8.0.jar

    public void getConn()
    {
        //获取jedis连接
        Jedis jedis = new Jedis("127.0.0.1",6379);
        //获取redis中以FIELD开头的key
        Set<String> keys = jedis.keys("FIELD*");
        for(String key : keys)
        {
            System.out.println(key);
        }
    }


2、java获取jedis连接池

如果每次连接redis都new1个Jedis的话,势必耗费很多资源,这里就提到redis连接池。

所需jar包

commons-pool2-2.3.jar

jedis-2.8.0.jar

    public class RedisUtil
    {
        private static JedisPool pool = null;
       
        /**
         * 获取jedis连接池
         * */
        public static JedisPool getPool()
        {
            if(pool == null)
            {
                //创建jedis连接池配置
                JedisPoolConfig config = new JedisPoolConfig();
                //最大连接数
                config.setMaxTotal(100);
                //最大空闲连接
                config.setMaxIdle(5);
                //创建redis连接池
                pool = new JedisPool(config,"127.0.0.1",6379,超时时长);
            }
            return pool;
        }
       
        /**
         * 获取jedis连接
         * */
        public static Jedis getConn()
        {
            return getPool().getResource();
        }
    }


新版本jedis的jar包获取连接池,使用完后用jedis.close()归还连接:

    @Test
        public void testPool()
        {
            //获取jedis连接
            Jedis jedis = RedisUtil.getConn();   
            String value = jedis.get(key);
            //使用之后记得关闭连接
            jedis.close();
        }



老版本的jedis jar获取连接,使用完要用pool.returnResource(jedis);归还连接

    public void testPool()
    {
        //获取jedis连接
        JedisPool pool = RedisUtil.getPool();
        Jedis jedis = pool.getResource();
        String value = jedis.get(key);
        //使用之后记得关闭连接
        pool.returnResource(jedis);
    }
---------------------

评论