jedis簡介和使用

1.jedis簡介

jedis是一個java實現的redis客戶端連接工具。常用的還有redisson,jedis跟接近於原生的操作,而redisson跟適合用於分佈式,提供了分佈式鎖,以及其他多種數據結構。
jedis使用非常簡單
直接引入依賴

<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.9.0</version>
		</dependency>
Jedis jedis = new Jedis("locahost",6379);

jedis使用完後記得調用其close方法釋放其資源,jedis是線程不完全,多線程使用同一個jedis實例,會出現併發問題,原因是底層共用了一個輸入輸出流。避免這個問題每次使用可以new 一個新的Jedis實例,但是創建實例的代價是昂貴的,jedis提供,jedisPool,和數據庫池,線程池的思想類似,就是保存一定的jedis實例,需要的話就拿來用。

2.簡單使用

package com.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.Properties;

public class JedisUtil {

    private final static Logger LOGGER = LoggerFactory.getLogger(JedisUtil.class);
    private JedisPool jedisPool = null;
    /**
     * 不存在才設置
     */
    public static final String NX = "NX";
    /**
     * 存在才設置
     */
    public static final String XX = "XX";
    //秒
    public static final String EX = "EX";
    //毫秒
    public static final String PX = "PX";

    static {

    }

    public JedisUtil() throws IOException {
        Properties properties = new Properties();
        URL resource = JedisUtil.class.getResource("redis.properties");
        properties.load(resource.openStream());
        JedisPoolConfig config = new JedisPoolConfig();
        Integer maxActive = Integer.parseInt(properties.getProperty("jedis.pool.maxActive"));
        Integer maxIdle = Integer.parseInt(properties.getProperty("jedis.pool.maxIdle"));
        Long maxWait = Long.parseLong(properties.getProperty("jedis.pool.maxWait"));
        Boolean testOnBorrow = Boolean.valueOf(properties.getProperty("jedis.pool.testOnBorrow"));
        Boolean testOnReturn = Boolean.valueOf(properties.getProperty("jedis.pool.testOnReturn"));
        config.setMaxTotal(maxActive);
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWait);
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);
        jedisPool = new JedisPool(config,properties.getProperty("jedis.pool.ipAddress"),Integer.parseInt(properties.getProperty("jedis.pool.port")));
    }


    private Jedis getJedis(){
        return jedisPool.getResource();
    }

    public String set(byte[] key, byte[] value, String nxxx, String expx,
                    long time){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.set(key,value,nxxx.getBytes("utf-8"),expx.getBytes("utf-8"),time);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnObject(jedis);
        }
        return null;
    }


    public String setString(String key,String val){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.set(key,val);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnObject(jedis);
        }
        return  null;
    }

    /**
     * 設置集合值
     * @param key
     * @param val
     * @return
     */
    public Long lpush(byte[] key,byte[] ... val){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.lpush(key,val);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnObject(jedis);
        }
        return  null;
    }

    /**
     * 設置集合值
     * @param key
     * @return
     */
    public List<byte[]> getAllListValues(byte[] key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            Object vals = jedis.eval("local len = redis.call('llen',KEYS[1]) return redis.call('lrange',KEYS[1],0,len)".getBytes(),1,key);
            return (List<byte[]>) vals;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnObject(jedis);
        }
        return  null;
    }


    public String getString(String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnObject(jedis);
        }
        return  null;
    }

    /**
     * 返回刪除的個數
     * @param key
     * @return
     */
    public Long del(byte[] key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.del(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnObject(jedis);
        }
        return  null;
    }

    public byte[] get(byte[] key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnObject(jedis);
        }
        return  null;
    }


    private void returnObject(Jedis jedis){
        if(jedis != null){
            jedis.close();
        }
    }


    /**
     * 序列化
     * @param obj
     * @return
     */
    public static byte [] serialize(Object obj){
        ObjectOutputStream objectOutputStream=null;
        ByteArrayOutputStream byteArrayOutputStream=null;
        try {
            byteArrayOutputStream=new ByteArrayOutputStream();
            objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(obj);
            byte[] bytes=byteArrayOutputStream.toByteArray();
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //反序列化
    public static Object unSerizlize(byte[] byt){
        ObjectInputStream objectInputStream=null;
        ByteArrayInputStream bis=null;
        bis=new ByteArrayInputStream(byt);
        try {
            objectInputStream=new ObjectInputStream(bis);
            Object obj=objectInputStream.readObject();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}


發佈了114 篇原創文章 · 獲贊 21 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章