1. 程式人生 > >java 操作redis (Spring 連線池)

java 操作redis (Spring 連線池)

Spring XML 配置檔案

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"
>
<context:property-placeholder location="classpath*:/jedis/jedis.properties" /> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!--最大連線數 --> <property name="maxTotal" value="${redis.pool.maxActive}" /> <!--最大空閒連線數 -->
<property name="maxIdle" value="${redis.pool.maxIdle}" /> <!--初始化連線數 --> <property name="minIdle" value="${redis.pool.minIdle}" /> <!--最大等待時間 --> <property name="maxWaitMillis" value="${redis.pool.maxWait}" /> <!--定時對執行緒池中空閒的連結進行validateObject校驗 --> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="true" /> <!--在進行returnObject對返回的connection進行validateObject校驗 --> <property name="testOnReturn" value="true" /> </bean> <bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy"> <constructor-arg index="0" ref="jedisPoolConfig" /> <constructor-arg index="1" value="${redis.host}" /> <constructor-arg index="2" value="${redis.port}" type="int" /> <constructor-arg index="3" value="${redis.timeout}" type="int" /> </bean> </beans>

jedis.properties

redis.host=${redis.host}
redis.port=${redis.port}
redis.password=${redis.password}
redis.timeout=${redis.timeout}
redis.pool.maxActive=${redis.pool.maxActive}
redis.pool.maxIdle=${redis.pool.maxIdle}
redis.pool.minIdle=${redis.pool.minIdle}
redis.pool.maxWait=${redis.pool.maxWait}

JAVA 類 :JedisCacheClient

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fctx.ordercenter_common.utils.JsonUtil;
import com.fctx.ordercenter_webapp.common.lib.WebConfigConstant;

/**
 * @Title: JedisCacheClient.java
 * @Package com.tctx.common.redis
 * @Description: redis 操作資料庫配置類
 */
@Component("jedisCacheClient")
public class JedisCacheClient {

    private Logger log = Logger.getLogger(JedisCacheClient.class);

    @Autowired
    private JedisPool jedisPool;


    /**
     * 
      * setVExpire(設定key值,同時設定失效時間 秒)
      * @Title: setVExpire
      * @param @param key
      * @param @param value
      * @param @param seconds
      * @param index 具體資料庫
      * @return void
      * @throws
     */
    public <V> void setVExpire(String key, V value,int seconds,int index) {
        String json = JSON.toJSONString(value);
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(index);
            jedis.set(WebConfigConstant.PROJECT+key, json);
            jedis.expire(WebConfigConstant.PROJECT+key, seconds);
        } catch (Exception e) {
            log.error("setV初始化jedis異常:" + e);
            if (jedis != null) {
                jedisPool.returnBrokenResource(jedis);
            }
        } finally {
            closeJedis(jedis);
        }

    }
    /**
     * 
      * (存入redis資料)
      * @Title: setV
      * @param @param key
      * @param @param value
      * @param index 具體資料庫 
      * @return void
      * @throws
     */
    public <V> void setV(String key, V value,int index) {
        String json = JSON.toJSONString(value);
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(index);
            jedis.set(WebConfigConstant.PROJECT+key, json);
        } catch (Exception e) {
            log.error("setV初始化jedis異常:" + e);
            if (jedis != null) {
                jedisPool.returnBrokenResource(jedis);
            }
        } finally {
            closeJedis(jedis);
        }

    }

    /**
     * 
      * getV(獲取redis資料資訊)
      * @Title: getV
      * @param @param key
      * @param index 具體資料庫 0:常用資料儲存      3:session資料儲存
      * @param @return
      * @return V
      * @throws
     */
    @SuppressWarnings("unchecked")
    public <V> V getV(String key,int index) {
        String value = "";
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(index);
            value = jedis.get(WebConfigConstant.PROJECT+key);
        } catch (Exception e) {
            log.error("getV初始化jedis異常:" + e);
            if (jedis != null) {
                jedisPool.returnBrokenResource(jedis);
            }
        } finally {
            closeJedis(jedis);
        }
        return (V)JSONObject.parse(value);
    }
    /**
     * 
      * getVString(返回json字串)
      * @Title: getVString
      * @param @param key
      * @param @param index
      * @param @return
      * @return String
      * @throws
     */
    public String getVStr(String key,int index) {
        String value = "";
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(index);
            value = jedis.get(WebConfigConstant.PROJECT+key);
        } catch (Exception e) {
            log.error("getVString初始化jedis異常:" + e);
            if (jedis != null) {
                jedisPool.returnBrokenResource(jedis);
            }
        } finally {
            closeJedis(jedis);
        }
        return value;
    }

    /**
     * 
     * Push(存入 資料到佇列中)
     * 
     * @Title: Push
     * @param @param key
     * @param @param value
     * @return void
     * @throws
     */
    public <V> void Push(String key, V value) {
        String json = JSON.toJSONString(value);
        Jedis jedis = null;
        try {
            log.info("存入 資料到佇列中");
            jedis = jedisPool.getResource();
            jedis.select(15);
            jedis.lpush(key, json);
        } catch (Exception e) {
            log.error("Push初始化jedis異常:" + e);
            if (jedis != null) {
                jedisPool.returnBrokenResource(jedis);
            }
        } finally {
            closeJedis(jedis);
        }
    }
    /**
     * 
     * Push(存入 資料到佇列中)
     * 
     * @Title: PushV
     * @param  key
     * @param value
     * @param dBNum
     * @return void
     * @throws
     */
    public <V> void PushV(String key, V value,int dBNum) {
        String json = JSON.toJSONString(value);
        Jedis jedis = null;
        try {
            log.info("存入 資料到佇列中");
            jedis = jedisPool.getResource();
            jedis.select(dBNum);
            jedis.lpush(key, json);
        } catch (Exception e) {
            log.error("Push初始化jedis異常:" + e);
            if (jedis != null) {
                jedisPool.returnBrokenResource(jedis);
            }
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * 
     * Push(存入 資料到佇列中)
     * 
     * @Title: Push
     * @param @param key
     * @param @param value
     * @return void
     * @throws
     */
    public <V> void PushEmail(String key, V value) {
        String json = JsonUtil.entity2Json(value);
        Jedis jedis = null;
        try {
            log.info("存入 資料到佇列中");
            jedis = jedisPool.getResource();
            jedis.select(15);
            jedis.lpush(key, json);
        } catch (Exception e) {
            log.error("Push初始化jedis異常:" + e);
            if (jedis != null) {
                jedisPool.returnBrokenResource(jedis);
            }
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * 
     * Pop(從佇列中取值)
     * 
     * @Title: Pop
     * @param @param key
     * @param @return
     * @return V
     * @throws
     */
    @SuppressWarnings("unchecked")
    public <V> V Pop(String key) {
        String value = "";
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(15);
            value = jedis.rpop(WebConfigConstant.PROJECT+key);
        } catch (Exception e) {
            log.error("Pop初始化jedis異常:" + e);
            if (jedis != null) {
                jedisPool.returnBrokenResource(jedis);
            }
        } finally {
            closeJedis(jedis);
        }
        return (V) value;
    }


    /**
     * 
     * expireKey(限時存入redis伺服器)
     * 
     * @Title: expireKey
     * @param @param key
     * @param @param seconds
     * @return void
     * @throws
     */
    public void expireKey(String key, int seconds) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(3);
            jedis.expire(WebConfigConstant.PROJECT+key, seconds);
        } catch (Exception e) {
            log.error("Pop初始化jedis異常:" + e);
            if (jedis != null) {
                jedisPool.returnBrokenResource(jedis);
            }
        } finally {
            closeJedis(jedis);
        }

    }

    /**
     * 
     * closeJedis(釋放redis資源)
     * 
     * @Title: closeJedis
     * @param @param jedis
     * @return void
     * @throws
     */
    public void closeJedis(Jedis jedis) {
        try {
            if (jedis != null) {
                jedisPool.returnBrokenResource(jedis);
            }
        } catch (Exception e) {
            log.error("釋放資源異常:" + e);
        }
    }

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

}