Redis快速入门(三):jedis连接池&相关的工具类

1、jedis概述

Jedis是Redis官方推荐的Java连接开发工具。要在Java开发中使用好Redis中间件,必须对Jedis熟悉才能写成漂亮的代码。

2、jedis基本使用

Jedis的基本使用非常简单,只需要创建Jedis对象的时候指定host(主机名),port(端口), password(密码)即可。当然,Jedis对象又很多构造方法,都大同小异,只是对应和Redis连接的socket的参数不一样而已:

import redis.clients.jedis.Jedis;

public class JedisTest {
    
    


    public static Jedis init(String host,Integer port){
    
    
        Jedis jedis = new Jedis(host, port);
        return jedis;
    }

    public static Jedis init(String host){
    
    
        Jedis jedis = new Jedis(host);
        return jedis;
    }

    public static Jedis init(String host,Integer port,String password){
    
    
        Jedis jedis = new Jedis(host, port);
        jedis.auth(password);
        return jedis;
    }
}

3、连接池使用

jedis连接池是基于apache-commons pool2实现的。在构建连接池对象的时候,需要提供池对象的配置对象,及JedisPoolConfig(继承自GenericObjectPoolConfig)。我们可以通过这个配置对象对连接池进行相关参数的配置(如最大连接数,最大空数等)。

* 使用:
1.创建JedisPool连接池对象 
2.调用方法 getResource()方法获取Jedis连接
//0.创建一个配置对象 
JedisPoolConfig config = new JedisPoolConfig(); 
config.setMaxTotal(50); 
config.setMaxIdle(10); //最大空闲时间

 //1.创建Jedis连接池对象
		        JedisPool jedisPool = new 		
		        JedisPool(config,"localhost",6379);
		
		        //2.获取连接
		        Jedis jedis = jedisPool.getResource();
		        //3. 使用
		        jedis.set("hehe","heihei");
				//4. 关闭 归还到连接池中
				 jedis.close();
2、工具类
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class JedisPoolUtils {
    
    

    private static JedisPool jedisPool;

    static {
    
    
        //读取配置文件
        InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
        //创建Properties对象
        Properties pro = new Properties();
        //关联文件
        try {
    
    
            pro.load(is);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        //获取数据,设置到JedisPoolConfig中
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
        config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));

        //初始化JedisPool
        jedisPool = new JedisPool(config, pro.getProperty("host"), Integer.parseInt(pro.getProperty("port")));
}

                    /**
 				     * 获取连接方法
 				     */
        

    public static Jedis getJedis() {
    
    
		return jedisPool.getResource();
	}

}

上一章:Redis快速入门(二):redis五种常见的数据结构
下一章:跟新中。。

猜你喜欢

转载自blog.csdn.net/weixin_46822085/article/details/109355035