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

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