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();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值