使用 JedisPool 来获取 Jedis 连接

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a909301740/article/details/81914677

jedis 作为一个数据库同样也有数据库连接池 JedisPool,封装了一个简单的获取 Jedis 连接池的工具类(单例模式):

package com.qjl.pems.test;

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

public class JedisPoolUtil {

    private static JedisPool JEDIS_POOL = null;

    private JedisPoolUtil() {}

    public static JedisPool getJedisPool() {
        if (JEDIS_POOL == null) {
            synchronized(JedisPoolUtil.class) {
                if (JEDIS_POOL == null) {
                    JedisPoolConfig poolConfig = new JedisPoolConfig();
                    poolConfig.setMaxTotal(500); // 500个连接
                    poolConfig.setMaxIdle(32); // 最大的空闲连接
                    poolConfig.setMaxWaitMillis(100 * 1000); // 最长的等待时间
                    poolConfig.setTestOnBorrow(true); // 获得一个jedis连接时检测可用性

                    JEDIS_POOL = new JedisPool(poolConfig, "192.168.198.130", 6379);
                }
            }
        }
        return JEDIS_POOL;
    }   
}

测试类如下:

package com.qjl.pems.test;

import java.util.Set;

import org.junit.Test;

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

/**
 * 类描述:测试Redis的客户端Jedis
 * 全限定性类名: com.qjl.pems.test.JedisTest
 * @author 曲健磊
 * @date 2018年8月15日上午8:18:19
 * @version V1.0
 */
public class JedisTest {

    /**
     * 测试jedis连接池
     */
    @Test
    public void testJedisPool() {
        // 1.获取连接池
        JedisPool jedisPool = JedisPoolUtil.getJedisPool();
        // 2.获取某个连接
        Jedis jedis = jedisPool.getResource();
        // 3.设置键值
        jedis.slaveofNoOne(); // 成为 master
        jedis.set("a", "b");
        // 4.获取键对应的值
        System.out.println(jedis.get("a"));
    }

}

猜你喜欢

转载自blog.csdn.net/a909301740/article/details/81914677