Java与redis交互、Jedis连接池JedisPool

Java与redis交互比较常用的是Jedis。

先导入jar包:

commons-pool2-2.3.jar

jedis-2.7.0.jar

基本使用:

public class RedisTest1 {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("localhost",6379);
        jedis.set("username","chichung");
        jedis.close();
    }
}

Jedis对象基本和redis的命令一模一样,这里不啰嗦了。

 

  • JedisPool连接池

 类似于mysql连接池,jedis也有连接池。

基本使用如下:

public class RedisTest2 {
    public static void main(String[] args) {
        // 比较特殊的是,redis连接池的配置首先要创建一个连接池配置对象
        JedisPoolConfig config = new JedisPoolConfig();
        // 当然这里还有设置属性的代码

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

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

        // 使用

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

一般可以抽取出来作为一个工具类使用:

例如有一个配置文件jedis.properties。

里面的内容如下:

host=127.0.0.1
port=6379
maxTotal=50
maxIdle=10

工具类代码如下:

package com.chichung.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;

public class JedisPoolUtils {
    private static JedisPool jedisPool;

    static {
        InputStream is = JedisPoolUtils.class.getClassLoader().getResourceAsStream("jedis.properties");
        Properties properties = new Properties();
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(Integer.parseInt(properties.getProperty("maxTotal")));
        config.setMaxIdle(Integer.parseInt(properties.getProperty("maxIdle")));

        jedisPool = new JedisPool(config,
                properties.getProperty("host"),
                Integer.parseInt(properties.getProperty("port")));

    }

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


}

猜你喜欢

转载自www.cnblogs.com/chichung/p/10360744.html