redis:java连接操作redis的jedis驱动包的简单使用

上一篇已经把redis安装在了linux服务器上了,接下来使用java代码去对redis进行操作,这里就需要用到redis的驱动包,和mysql数据库类似。

引入jedis(maven工程方式):


引入包后就可以使用了,使用Jedis对象就可以对redis数据库进行操作。


使用连接池的方式对redis进行连接操作:


下面我们尝试一下制作一个redis连接池的工具类:

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;

/**
 * 自制redis连接池工具类
 */
public class MyRedisPool {
    //声明静态的JedisPool属性
    private static JedisPool jedisPool = null;
    //静态块
    static {
        //获取inputStream流 读取redis.properties配置文件
        InputStream inputStream = MyRedisPool.class.getClassLoader().
                getResourceAsStream("redis.properties");
        //Properties集合获取配置文件中的配置属性
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //创建JedisPoolConfig连接池配置对象
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(Integer.parseInt(properties.getProperty("redis.maxTotal")));
        poolConfig.setMaxIdle(Integer.parseInt(properties.getProperty("redis.maxIdle")));
        poolConfig.setMinIdle(Integer.parseInt(properties.getProperty("redis.minIdle")));
        //创建redis连接池,把配置对象给她
        jedisPool = new JedisPool(poolConfig, properties.getProperty("redis.url"), Integer.parseInt(properties.getProperty("redis.port")));
    }

    /**
     * 得到redis操作资源对象方法
     * @return Jedis操作资源对象
     */
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }
}

创建redis.properties配置文件,配置文件内容:

redis.maxTotal=50
redis.maxIdle=20
redis.minIdle=10
redis.url=127.0.0.1
redis.port=6379

测试一下我们自己操作的工具类:


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值