redis工具類 ----RedisPoolUtil


這里介紹一下,這個工具類不是在分布式環境下來用的,就是我們平常使用的,單機狀況下,為什么博主開頭要這樣強調呢?因為,之前見網上有些博友有這樣封裝的,也有RedisShardedPoolUtil 封裝的 ,剛開始不是很明白,現在知道了,后者是在分布式的場景下使用的。好啦。現在讓我們來code了~~~~

 

首先來大致介紹下吧,redis的工具類很簡單,就是先創建一個redis連接池(引入第三方的jar包就行),像數據庫連接池一樣,然后,需要的參數寫在配置文件中,創建連接池這個類  RedisPool.java   需要兩個方法,一個從連接池得到資源redis,一個是放回redis資源。

然后,再寫一個專門操控redis的  ‘增刪改查’  方法。這就可以。 不多說,老規矩,開箱即用。上代碼!!!

 

pom.xml
<dependencies>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
        <!--加速開發的工具,可以省略getset和日志類,只需要注解就可以-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.6</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>


        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.1.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.logback-extensions</groupId>
            <artifactId>logback-ext-spring</artifactId>
            <version>0.1.1</version>
        </dependency>
    </dependencies>
View Code

RedisPool.java
這里強調一下,redis的pom是2.9 所以回收資源是close方法,之前的pool.returnBrokenResource(jedis);
和pool.returnResource(jedis);已經被官方棄用了。這點注意。
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by 敲代碼的卡卡羅特
 */
@Slf4j
public class RedisPool {
    private static JedisPool pool;//jedis連接池
    private static Integer maxTotal = Integer.parseInt(PropertiesUtil.getProperty("redis.max.total","20")); //最大連接數
    private static Integer maxIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle","20"));//在jedispool中最大的idle狀態(空閑的)的jedis實例的個數
    private static Integer minIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.min.idle","20"));//在jedispool中最小的idle狀態(空閑的)的jedis實例的個數

    private static Boolean testOnBorrow = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.borrow","true"));//在borrow一個jedis實例的時候,是否要進行驗證操作,如果賦值true。則得到的jedis實例肯定是可以用的。
    private static Boolean testOnReturn = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.return","true"));//在return一個jedis實例的時候,是否要進行驗證操作,如果賦值true。則放回jedispool的jedis實例肯定是可以用的。

    private static String redisIp = PropertiesUtil.getProperty("redis1.ip");
    private static Integer redisPort = Integer.parseInt(PropertiesUtil.getProperty("redis1.port"));


    private static void initPool(){
        JedisPoolConfig config = new JedisPoolConfig();

        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);

        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);

        config.setBlockWhenExhausted(true);//連接耗盡的時候,是否阻塞,false會拋出異常,true阻塞直到超時。默認為true。

        pool = new JedisPool(config,redisIp,redisPort,1000*2);
    }

    static{
        initPool();
    }

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


    public static void close(Jedis jedis){
        try {
            if (jedis != null) {
                jedis.close();
            }
        } catch (Exception e) {
            log.error("return redis resource exception", e);
        }
    }


    public static void main(String[] args) {
        Jedis jedis = pool.getResource();
        jedis.set("lzh","liuzhonghua");
        close(jedis);

        pool.destroy();//臨時調用,銷毀連接池中的所有連接
        System.out.println("program is end");


    }







}
View Code
 
        
RedisPoolUtil.java   代碼很簡單  方法就不一一介紹了。看不懂的留言問我
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;

/**
 * Created by 敲代碼的卡卡羅特
 */
@Slf4j
public class RedisPoolUtil {


    /**
     * 設置key的有效期,單位是秒
     * @param key
     * @param exTime
     * @return
     */
    public static Long expire(String key,int exTime){
        Jedis jedis = null;
        Long result = null;
        try {
            jedis = RedisPool.getJedis();
            result = jedis.expire(key,exTime);
        } catch (Exception e) {
            log.error("expire key:{} error",key,e);
            RedisPool.close(jedis);
            return result;
        }
        RedisPool.close(jedis);
        return result;
    }

    //exTime的單位是秒
    public static String setEx(String key,String value,int exTime){
        Jedis jedis = null;
        String result = null;
        try {
            jedis = RedisPool.getJedis();
            result = jedis.setex(key,exTime,value);
        } catch (Exception e) {
            log.error("setex key:{} value:{} error",key,value,e);
            RedisPool.close(jedis);
            return result;
        }
        RedisPool.close(jedis);
        return result;
    }

    public static String set(String key,String value){
        Jedis jedis = null;
        String result = null;

        try {
            jedis = RedisPool.getJedis();
            result = jedis.set(key,value);
        } catch (Exception e) {
            log.error("set key:{} value:{} error",key,value,e);
            RedisPool.close(jedis);
            return result;
        }
        RedisPool.close(jedis);
        return result;
    }

    public static String get(String key){
        Jedis jedis = null;
        String result = null;
        try {
            jedis = RedisPool.getJedis();
            result = jedis.get(key);
        } catch (Exception e) {
            log.error("get key:{} error",key,e);
            RedisPool.close(jedis);
            return result;
        }
        RedisPool.close(jedis);
        return result;
    }

    public static Long del(String key){
        Jedis jedis = null;
        Long result = null;
        try {
            jedis = RedisPool.getJedis();
            result = jedis.del(key);
        } catch (Exception e) {
            log.error("del key:{} error",key,e);
            RedisPool.close(jedis);
            return result;
        }
        RedisPool.close(jedis);
        return result;
    }

    public static void main(String[] args) {
        Jedis jedis = RedisPool.getJedis();

        jedis.setex("name",100,"lzh");

        System.out.println("end");


    }


}
View Code

 

再配上讀取配置文件的工具類  PropertiesUtil  需要注意的是,這個文件名寫死了,就從這一個文件名中讀取參數。你也可以再封裝一下。
我這里就不麻煩了。
PropertiesUtil.java
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * Created by 敲代碼的卡卡羅特
 */
@Slf4j
public class PropertiesUtil {


    private static Properties props;

    static {
        String fileName = "mmall.properties";
        props = new Properties();
        try {
            props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName),"UTF-8"));
        } catch (IOException e) {
            log.error("配置文件讀取異常",e);
        }
    }

    public static String getProperty(String key){
        String value = props.getProperty(key.trim());
        if(StringUtils.isBlank(value)){
            return null;
        }
        return value.trim();
    }

    public static String getProperty(String key,String defaultValue){

        String value = props.getProperty(key.trim());
        if(StringUtils.isBlank(value)){
            value = defaultValue;
        }
        return value.trim();
    }

    public static void main(String[] arg){
        System.out.println(PropertiesUtil.getProperty("redis.port"));
    }

}
View Code

  mmall.properties

#redis config start

redis1.ip=127.0.0.1
redis1.port=6379


##Tips:以上redis1和redis2的ip和port改成你自己的喲

#最大連接數
redis.max.total=20

#最大空閑數
redis.max.idle=10

#最小空閑數
redis.min.idle=2

#從jedis連接池獲取連接時,校驗並返回可用的連接
redis.test.borrow=true

#把連接放回jedis連接池時,校驗並返回可用的連接
redis.test.return=false


#redis config end
View Code

 

ok,大功告成
 









 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM