Jedis 下载使用、连接池以及工具类。

下载 Jedis 和 Commons-Pool

使用 Redis 官方推荐的 Jedis,在 java 应用中操作 Redis。Jedis 几乎涵盖了 Redis 的所有命令。操作 Redis 的命令在 Jedis 中以方法的形式出现。jedis 完全兼容 redis 2.8.x and 3.x.x

下载地址
搜索 jedis。在 Download 处,点击 jar在这里插入图片描述

Jedis 对象并不是线程安全的,在多线程下使用同一个 Jedis 对象会出现并发问题。为了避免每次使用 Jedis 对象时都需要重新构建,Jedis 提供了 JedisPool。JedisPool 是基于Commons Pool 2 实现的一个线程安全的连接池

在刚才的网站搜索 commons-pool2。在 Download 处,点击 jar在这里插入图片描述

常用方法
new Jedis(host, port)	创建jedis对象,参数host是redis服务器地址,参数port是redis服务端口
set(key,value)	设置字符串类型的数据
get(key)	获得字符串类型的数据
hset(key,field,value)	设置哈希类型的数据
hget(key,field)	获得哈希类型的数据
lpush(key,values)	设置列表类型的数据
lpop(key)	列表左面弹栈
rpop(key)	列表右面弹栈
del(key)	删除指定的key

Jedis的基本操作

public class RedisUtilSnapshot {
    public static void main(String[] args) {
        //1. 导入jar包
        //2. 建立redis的连接
        Jedis connection = new Jedis("localhost", 6379);

        //3. 使用该连接, 执行命令
        connection.set("name", "zhangsan");
        
        //4. 关闭连接
        connection.close();
    }
}

Jedis连接池

jedis连接资源的创建与销毁是很消耗程序性能,所以jedis为我们提供了jedis的池化技术,jedisPool在创建时初始化一些连接资源存储到连接池中,使用jedis连接资源时不需要创建,而是从连接池中获取一个资源进行redis的操作,使用完毕后,不需要销毁该jedis连接资源,而是将该资源归还给连接池,供其他请求使用。

    /**
     * jedis连接池使用
     */
    @Test
    public void JedisPool () {
        //创建一个配置对象
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(50); //设置最大连接数
        config.setMaxIdle(10); //空闲连接数

        //创建Jedis连接池对象
        JedisPool jedisPool = new JedisPool(config,"localhost",6379);

        //获取连接
        Jedis jedis = jedisPool.getResource();

        //使用
        jedis.set("name", "wangwu");

        //关闭 归还到连接池中
        jedis.close();

    }

Jedis工具类

/**
 * JedisPool工具类
 * 加载配置文件,配置连接池的参数
 * 提供获取连接的方法
 */
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();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章