JedisUtil

本文介绍了如何在Java中使用Jedis基础写法和连接池进行Redis操作,包括设置键值对、关闭连接及配置JedisPool实现资源管理。
摘要由CSDN通过智能技术生成

Jedis(Java操控Redis)

基础写法

  1. jar包:jedis-2.9.0.jar
  2. 创建Jedis对象:
    Jedis jedis = new Jedis(“IP地址”,端口号);
  3. 可以对Jedis对象进行操作(添加,查询,删除等)
    例:添加:jedis.set(“key”,”value”);
  4. 关闭:Jedis:jedis.close()

连接池

  1. 连接池jar包:commons-pool2-2.2.jar
  2. Jedis连接池的配置:
    JedisPoolConfig config = new JedisPoolConfig();
    配置方式例:
    连接池的最大值config.setMaxTotal(100);
    按照配置新建连接池:
    JedisPool jedisPool = new JedisPool(config,“IP地址”,端口号);
  3. 获取redis的资源:Jedis jedis = jedisPool.getResource();
  4. 关闭Jedis:jedis.close()

JedisUtil的写法

public static Jedis jedis;
    public static Jedis getJedisConnection(){


        if (jedis==null) {
        //配置文件redis.properties内容 在 下方 另附
            InputStream is=JedisPool.class.getResourceAsStream("/redis.properties");
            Properties prop= new Properties();
            try {
                prop.load(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String host = prop.getProperty("host");
            int port = new Integer(prop.getProperty("prot"));
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(new Integer(prop.getProperty("maxTotal")));
            config.setMaxIdle(new Integer(prop.getProperty("maxIdle")));
            config.setMaxWaitMillis(new Integer(prop.getProperty("maxWaitMillis")));
            JedisPool pool = new JedisPool(config, host, port);
            return pool.getResource();
        }
        return jedis;
    }

配置文件 redis.properties 内容

host=127.0.0.1
post=6379
maxIdle=10
maxWaitMillis=10000
maxTotal=100
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值