java Jedis api:redis集群api JedisCluster、redis连接池api JedisPool

日萌社

人工智能AI:Keras PyTorch MXNet TensorFlow PaddlePaddle 深度学习实战(不定时更新)



    参数名 				默认值								含义
    maxActive			8								连接池中最大连接数
    maxIdle				8								连接池中最大空闲的连接数
    minIdle				0								连接池中最少空闲的连接数
    maxWaitMillis		-1:表示永远不超时,一直等。	当连接池资源用尽后,调用者的最大等待时间(单位为毫秒),一般不建议使用默认值
    jmxEnabled			true							是否开启jmx监控,如果应用开启了jmx端口并且jmxEnabled设置为true,
                                                        就可以通过jconsole或者jvisualvm看到关于连接池的相关统计,
                                                        有助于了解连接池的使用情况,并且可以针对其做监控统计
    minEvictableIdleTimeMillis		30分钟				连接的最小空闲时间,达到此值后空闲连接将被移除
    numTestsPerEvictionRun			3					做空闲连接检测时,每次的采样数
    testOnBorrow					false				向连接池借用连接时是否做连接有效性检测(ping),无效连接会被移除,每次借用多执行一次ping命令
    testOnReturn					false				向连接池归还连接时是否做连接有效性检测(ping),无效连接会被移除,每次归还多执行一次ping命令
    testWhileIdle					false				向连接池借用连接时是否做连接空闲检测,空闲超时的连接会被移除
    timeBetweenEvictionRunsMillis	-1:表示不做检测	空闲连接的检测周期(单位为毫秒)
    blockWhenExhausted				true				当连接池用尽后,当调用者发现池子中没有资源时,调用者是否要等待,为false时会立即抛出异常不进行等待,默认true阻塞直到超时
                                                        这个参数是和maxWaitMillis对应的,只有当此参数为true时,maxWaitMillis才会生效

    JedisCluster包含了所有节点的连接池,建议JedisCluster使用单例。JedisCluster每次操作完成后,不需要管理连接池的借还,它在内部已经完成。
    JedisCluster不用执行close()操作,它会将所有的JedisPool执行destory操作。

    非集群状态下用Jedis获取redis连接,得到Jedis对象即可,一共有两种:
        1.利用Jedis构造器,仅限用于测试,在实际项目中肯定是用JedisPool。
                  Jedis(String host);
                  Jedis(String host , int port);
        2.利用JedisPool
                主要是利用Jedis jedis=jedisPool.getResource();
                JedisPool有N多个构造器,常用的构造器参数有GenericObjectPoolConfig poolConfig,String host,int port,int timeout,String password,
                创建GenericObjectPoolConfig对象时我们一般用其子类JedisPoolConfig (redis.clients.jedis.JedisPoolConfig),timeout是连接redis服务器的超时时间,
                以毫秒为单位,一般设置为0,如果不设为0,则不可设置太小,如果设成1、2,那么可能因为网络原因在1毫秒、2毫秒之内没有连上服务器而报错。
                创建出一个JedisPool对象,然后调用其getResource()方法获取redis连接即可,之后就可以调用Jedis API操作redis了。
                jedis连接用完要释放即close,如果不close,则产生的连接会越来越多,当达到了最大连接数,再想获得连接,就会等待,当超过了最大等待时间后就会报异常。

    集群状态下:
            集群状态下用Jedis获取redis连接,是得到JedisCluster对象,之后对redis进行操作都是用此对象的方法进行的 

#redis.ips.ports 为自己定义的参数
# 内网
#redis.ips.ports=IP:端口,IP:端口,IP:端口
#外网
redis.ips.ports=IP:端口,IP:端口,IP:端口

##连接池最大连接数,默认是8。
redis.maxActive=80

##连接池中最大空闲的连接数
redis.maxIdle=10
##连接池中最小空闲的连接数
redis.minIdle=10
#空闲连接的检测周期(单位为毫秒),默认-1 表示不做检测
redis.timeBetweenEvictionRunsMillis=60000
#做空闲连接检测时,每次的采样数,默认3
redis.numTestsPerEvictionRun=10

#当连接池用尽后,调用者是否要等待,此参数和maxWaitMillis对应的,只有当此参数为true时,maxWaitMills才会生效。
#设置了blockWhenExhausted=false,那么调用者发现池子中没有资源时,会立即抛出异常不进行等待
#默认true 阻塞直到超时
redis.blockWhenExhausted=true
#当连接池用尽后,调用者的最大等待时间(单位为毫秒),默认值为-1 表示永不超时,一直等待,一般不建议使用默认值。
redis.maxWaitMillis = -1

##向连接池借用连接时是否做连接有效性检测(ping),无效连接会被移除,每次借出多执行一次ping命令,默认false。
redis.testOnBorrow=true
##向连接池归还连接时是否做连接有效性检测(ping),无效连接会被移除,每次借出多执行一次ping命令,默认false。
redis.testOnReturn=true
#向连接池借用连接时是否做连接空闲检测,空闲超时的连接会被移除,默认false。
redis.testWhileIdle=true

##当客户端闲置多长时间后关闭连接,如果指定为0,表示关闭该功能,单位毫秒
redis.timeout=3000

#连接的最小空闲时间,达到此值后空闲连接将被移除
redis.minEvictableIdleTimeMills=30000

 


redis集群api JedisCluster 

    private final static jedisTest jt = new jedisTest();

    public static JedisCluster getJedisCluster()
    {
        JedisCluster jedisCluster = null;

        try
        {
            //加载连接池配置文件
            /*
                InputStream in = 类名.class.getClassLoader().getResourceAsStream("/redis.properties");
                InputStream in = 类实例对象名.getClass().getResourceAsStream("/druid.properties");
                properties.load(in);
                Properties properties = new Properties();
                in.close();
            */
//            InputStream in = jedisTest.class.getClassLoader().getResourceAsStream("/redis.properties");
            InputStream in = jt.getClass().getResourceAsStream("/redis.properties");

            Properties props = new Properties();
            System.out.println();
            props.load(in);
            in.close();

            String hostAndPorts = props.getProperty("redis.ips.ports");
            System.out.println(hostAndPorts);

            if (jedisCluster == null)
            {
                int connectTimeOut = 10000;//连接超时
                int soTimeOut = 5000;//读写超时
                int maxAttemts = 10;//重试次数

                JedisPoolConfig poolConfig = new JedisPoolConfig();
                poolConfig.setMaxTotal(Integer.valueOf(props.getProperty("redis.maxActive"))); //连接池最大连接数
                poolConfig.setMaxIdle(Integer.valueOf(props.getProperty("redis.maxIdle")));//连接池中最大空闲的连接数
                //当连接池用尽后,调用者的最大等待时间(单位为毫秒),默认值为-1 表示永不超时,一直等待,一般不建议使用默认值。
//                poolConfig.setMaxWaitMillis(Long.valueOf(props.getProperty("redis.maxWaitMillis")));
                //向连接池借用连接时是否做连接有效性检测(ping),无效连接会被移除,每次借出多执行一次ping命令,默认false。
                poolConfig.setTestOnBorrow(Boolean.valueOf(props.getProperty("redis.testOnBorrow")));
                //向连接池归还连接时是否做连接有效性检测(ping),无效连接会被移除,每次借出多执行一次ping命令,默认false。
                poolConfig.setTestOnReturn(Boolean.valueOf(props.getProperty("redis.testOnReturn")));

                //连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
                poolConfig.setBlockWhenExhausted(true);
                //设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
                poolConfig.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
                //是否启用pool的jmx管理功能, 默认true
                poolConfig.setJmxEnabled(true);
                //MBean ObjectName = new ObjectName("org.apache.commons.pool2:type=GenericObjectPool,name=" + "pool" + i); 默 认为"pool", JMX不熟,具体不知道是干啥的...默认就好.
                poolConfig.setJmxNamePrefix("pool");
                //是否启用后进先出, 默认true
                poolConfig.setLifo(true);
                //获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
                poolConfig.setMaxWaitMillis(-1);
                //逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
                poolConfig.setMinEvictableIdleTimeMillis(1800000);
                //最小空闲连接数, 默认0
                poolConfig.setMinIdle(10);
                //每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
                //做空闲连接检测时,每次的采样数,默认3
                poolConfig.setNumTestsPerEvictionRun(3);
                //对象空闲多久后逐出, 当空闲时间>该值 且 空闲连接>最大空闲数 时直接逐出,不再根据MinEvictableIdleTimeMillis判断  (默认逐出策略)
                poolConfig.setSoftMinEvictableIdleTimeMillis(1800000);
                //在空闲时检查有效性, 默认false
                poolConfig.setTestWhileIdle(false);
                //逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
                poolConfig.setTimeBetweenEvictionRunsMillis(-1);

                Set jedisClusterNode = new HashSet();
                String[] hosts = hostAndPorts.split(",");

                for (String hostport : hosts)
                {
                    String[] ipport = hostport.split(":");

                    String ip = ipport[0];
                    int port = Integer.parseInt(ipport[1]);
                    jedisClusterNode.add(new HostAndPort(ip, port));
                }
                if (jedisCluster == null)
                {
                    jedisCluster = new JedisCluster(jedisClusterNode, connectTimeOut, soTimeOut, maxAttemts, poolConfig);
                }
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return jedisCluster;
    }

    public static void main(String[] args)
    {
//        JedisCluster jedisCluster = getJedisCluster();
        String ng = jedisCluster.set("ng", 0 + "");
        System.out.println(ng);
//
//        String ng1 = jedisCluster.get("ng");
//        System.out.println(ng1);
//        jedisCluster.close();

        //--------------------------------------------------

//        JedisPool jedisPool1 = getJedisPool1();
        JedisPool jedisPool2 = getJedisPool2();

        //从连接池获得连接
        Jedis jedis = jedisPool2.getResource();
        String result = jedis.get("ng");
        System.out.println("result:"+result);
        String a = jedis.set("ng", "0");
        System.out.println("设置的值:"+a);
        System.out.println("OK".equals(a));
        result = jedis.get("a");
        System.out.println(result);
        //每次jedis使用完毕后需要关闭,连接池回收资源。
        jedis.close();
        //系统结束前关闭连接池
        jedisPool2.close();
    }

    @Test
    public void testJedisCluster1() throws Exception
    {
        //连接集群使用JedisCluster对象
        Set<HostAndPort> nodes = new HashSet<>();
 
        nodes.add(new HostAndPort("IP", 2311));
        nodes.add(new HostAndPort("IP", 2311));
        nodes.add(new HostAndPort("IP", 2311));
        nodes.add(new HostAndPort("IP", 2312));
        nodes.add(new HostAndPort("IP", 2312));
        nodes.add(new HostAndPort("IP", 2312));
        //系统中可以是单例
        JedisCluster jedisCluster = new JedisCluster(nodes);
//        jedisCluster.set("ng", "0");
        String result = jedisCluster.get("a");
        System.out.println(result);
        //系统结束前关闭JedisCluster
        jedisCluster.close();
    }

    @Test
    public void testJedisCluster2() throws Exception
    {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        // 最大连接数
        poolConfig.setMaxTotal(1);
        // 最大空闲数
        poolConfig.setMaxIdle(1);
        // 最大允许等待时间,如果超过这个时间还未获取到连接,则会报JedisException异常:
        // Could not get a resource from the pool
        poolConfig.setMaxWaitMillis(1000);
        Set<HostAndPort> nodes = new LinkedHashSet<HostAndPort>();
        nodes.add(new HostAndPort("IP", 2311));
        nodes.add(new HostAndPort("IP", 2311));
        nodes.add(new HostAndPort("IP", 2311));
        nodes.add(new HostAndPort("IP", 2312));
        nodes.add(new HostAndPort("IP", 2312));
        nodes.add(new HostAndPort("IP", 2312));

        JedisCluster cluster = new JedisCluster(nodes, poolConfig);
        String name = cluster.get("ng");
        System.out.println("name:"+name);
//        cluster.set("age", "18");
//        System.out.println(cluster.get("age"));
        try
        {
            cluster.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

redis连接池api JedisPool

    public static JedisPool  getJedisPool1()
    {
        JedisPoolConfig config = new JedisPoolConfig();

        //连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
        config.setBlockWhenExhausted(true);
        //设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
        config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
        //是否启用pool的jmx管理功能, 默认true
        config.setJmxEnabled(true);
        //MBean ObjectName = new ObjectName("org.apache.commons.pool2:type=GenericObjectPool,name=" + "pool" + i); 默 认为"pool", JMX不熟,具体不知道是干啥的...默认就好.
        config.setJmxNamePrefix("pool");
        //是否启用后进先出, 默认true
        config.setLifo(true);
        //最大空闲连接数, 默认8个
        config.setMaxIdle(8);
        //最大连接数, 默认8个
        config.setMaxTotal(8);
        //获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
        config.setMaxWaitMillis(-1);
        //逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
        config.setMinEvictableIdleTimeMillis(1800000);
        //最小空闲连接数, 默认0
        config.setMinIdle(0);
        //每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
        config.setNumTestsPerEvictionRun(3);
        //对象空闲多久后逐出, 当空闲时间>该值 且 空闲连接>最大空闲数 时直接逐出,不再根据MinEvictableIdleTimeMillis判断  (默认逐出策略)
        config.setSoftMinEvictableIdleTimeMillis(1800000);
        //在获取连接的时候检查有效性, 默认false
        config.setTestOnBorrow(false);
        //在空闲时检查有效性, 默认false
        config.setTestWhileIdle(false);
        //逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
        config.setTimeBetweenEvictionRunsMillis(-1);

        JedisPool pool = new JedisPool(config, "IP",2311);
        return pool;
    }

    public static JedisPool  getJedisPool2()
    {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        // 最大连接数
        poolConfig.setMaxTotal(2);
        // 最大空闲数
        poolConfig.setMaxIdle(2);
        // 最大允许等待时间,如果超过这个时间还未获取到连接,则会报JedisException异常:
        // Could not get a resource from the pool
        poolConfig.setMaxWaitMillis(1000);
//        JedisPool pool = new JedisPool(poolConfig, "IP", 6379, 0, "123"); //密码 123
        JedisPool pool = new JedisPool(poolConfig, "IP", 2312, 0);

        Jedis jedis = null;
        try {
            for (int i = 0; i < 5; i++) {
                jedis = pool.getResource();
                jedis.set("foo" + i, "bar" + i);
                System.out.println("第" + (i + 1) + "个连接, 得到的值为" + jedis.get("foo" + i));
                // 用完一定要释放连接
                jedis.close();
            }
        } finally {
            pool.close();
        }
        return pool;
    }


    @Test
    public void testJedisPool() throws Exception {
        //创建一个连接池对象
        JedisPool jedisPool = new JedisPool("127.0.0.1", 6379);
        //从连接池获得连接
        Jedis jedis = jedisPool.getResource();
        String result = jedis.get("a");
        System.out.println(result);
        String a = jedis.set("a", "100");
        System.out.println("设置的值:"+a);
        System.out.println("OK".equals(a));
        result = jedis.get("a");
        System.out.println(result);
        //每次jedis使用完毕后需要关闭,连接池回收资源。
        jedis.close();
        //系统结束前关闭连接池
        jedisPool.close();
    }

    @Test
    public void testJedisPingPong() {
        //使用Jedis(redis的IP 或“hosts文件中redis的IP所映射的”域名, redis端口6379)
//        Jedis jedis = new Jedis("127.0.0.1", 6379);
        Jedis jedis = new Jedis("IP", 2312);

        String ping = jedis.ping();
        System.out.println(ping);
    }

    @Test
    public void testJedisSingle() throws Exception {
        //使用Jedis(redis的IP 或“hosts文件中redis的IP所映射的”域名, redis端口6379)
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.set("mytest", "1000");
        String result = jedis.get("mytest");
        System.out.println(result);
        jedis.close();
    }

 

 

 

 

 

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

あずにゃん

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值