您的位置:首页 > 数据库 > Redis

redis缓存方法

2016-05-20 09:43 363 查看
1 、 引用redis架包

              <dependency>

            <groupId>redis.clients</groupId>

            <artifactId>jedis</artifactId>

            <version>2.7.2</version>

            <scope>provided</scope>

           </dependency>

2、 redis公用方法:

        JedisSessionClient:

           package com.arec.jedisclient;

import java.io.InputStream;

import java.util.List;

import java.util.Map;

import java.util.Properties;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;

import redis.clients.jedis.JedisPoolConfig;

public class JedisSessionClient {

    private static JedisPool poolMaster;

    private JedisSessionClient() {

    }

    private static Logger log = LoggerFactory.getLogger(JedisSessionClient.class);

    static{

        try {

            Properties p = new Properties();

//                String filePath = new JedisClient().getClass().getResource("/").getPath() + "redisConfig.properties";

//                log.info("filePath:" + filePath);

//                InputStream is = new BufferedInputStream(new FileInputStream(filePath));

            ClassLoader classloader = Thread.currentThread().getContextClassLoader();

            InputStream is = classloader.getResourceAsStream("/redisConfig.properties");

            p.load(is);

            String redisSession = p.getProperty("redisSession").trim();

            // password = p.getProperty("password");

            int redisPort = Integer.parseInt(p.getProperty("redisPort").trim());

            int timeout = Integer.parseInt(p.getProperty("timeout").trim());

            JedisPoolConfig configMaster = new JedisPoolConfig();

            configMaster.setMaxTotal(30000);// 设置最大连接数

            configMaster.setMaxIdle(100); // 设置最大空闲数

            configMaster.setMinIdle(10);

            configMaster.setMaxWaitMillis(10000);// 设置超时时间

            configMaster.setTestWhileIdle(false);

            configMaster.setTestOnBorrow(false);

            poolMaster = new JedisPool(configMaster, redisSession,redisPort, timeout);

            log.info(">>>>>>>>>redisSession ip:" + redisSession);

            log.info(">>>>>>>>>redisSession port:"+redisPort);

            log.info(">>>>>>>>>redisSession timeout:"+timeout);

            log.info(">>>>>>>>>会话管理redis master连接池初始化成功...");

        } catch (Exception e) {

            log.info(">>>>>>>>>会话管理redis master连接池初始化失败,系统无法正常使用!!!");

            e.printStackTrace();

        }

        }

    private static Jedis getJedis() throws Exception {

        return poolMaster.getResource();

    }

    private static void returnResource(Jedis jedis) {

        if (jedis != null) {

            jedis.disconnect();

            poolMaster.returnResourceObject(jedis);

        }

    }

    /**

     * 向redis加入数据

     *

     * @param key

     * @param value

     * @throws Exception

     */

    public static void set(String key, String value) throws Exception {

        Jedis jedisMaster = null;

        if(null == key || "".equals(key.trim())){

            return;

        }

        try {

            jedisMaster = getJedis();

            jedisMaster.set(key, value);

        } finally {

            returnResource(jedisMaster);

        }

    }

    /**

     * 向redis加入String类型数据,并设置保存时间

     *

     * @param key

     * @param value

     * @param seconds

     *            数据保存时间(单位:秒)

     * @throws Exception

     */

    public static void set(String key, String value, int seconds)

            throws Exception {

        if(null == key || "".equals(key.trim())){

            return;

        }

        Jedis jedisMaster = null;

        try {

            jedisMaster = getJedis();

            jedisMaster.set(key, value);

            jedisMaster.expire(key, seconds);

            

        } finally {

            returnResource(jedisMaster);

        }

    }

    /**

     * 从redis取值

     *

     * @param key

     * @return

     * @throws Exception

     */

    public static String get(String key) throws Exception {

        if (null == key || "".equals(key.trim())) {

            return null;

        }

        Jedis jedisMaster = null;

        String value = null;

        try {

            jedisMaster = getJedis();

            value = jedisMaster.get(key);

        } finally {

            returnResource(jedisMaster);

        }

        return value;

    }

    public static long del(String key) throws Exception {

        if (null == key || "".equals(key.trim())) {

            return 0;

        }

        long value = 0;

        Jedis jedisMaster = null;

        try {

            jedisMaster = getJedis();

            value = jedisMaster.del(key);

        } finally {

            returnResource(jedisMaster);

        }

        return value;

    }

    

    public static long ttl(String key)throws Exception {

        long ttl = 0;

        if (null == key || "".equals(key.trim())) {

            return ttl;

        }

        Jedis jedisMaster = null;

        try {

            jedisMaster = getJedis();

            ttl = jedisMaster.ttl(key);

        }  finally {

            returnResource(jedisMaster);

        }

        return ttl;

    }

    

    public static List<String> hmget(String key,String... files) throws Exception {

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        List<String> list = null;

        try {

            jedisMaster = getJedis();

            list = jedisMaster.hmget(key,files);

        } finally {

            returnResource(jedisMaster);

        }

        return list;

    }

    

    public static void hmset(String key,Map<String,String> map,int seconds) throws Exception {

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        try {

            jedisMaster = getJedis();

            jedisMaster.hmset(key, map);

            if(seconds > 0){

                jedisMaster.expire(key, seconds);                

            }

        } finally {

        
4000
    returnResource(jedisMaster);

        }

    }

    

    public static void hset(String key,String mapKey,String mapValue,Integer seconds) throws Exception {

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        try {

            jedisMaster = getJedis();

            jedisMaster.hset(key, mapKey,mapValue);

            if(null != seconds){

                jedisMaster.expire(key, seconds);                

            }

        } finally {

            returnResource(jedisMaster);

        }

    }

    

    /**

     * <p>Title:JedisSessionClient.java</p>

     * <p>Description:续期</p>

     * @param key

     * @param seconds

     * @throws Exception

     */

    public static void expire(String key, int seconds)

            throws Exception {

        if(null == key || "".equals(key.trim())){

            return;

        }

        Jedis jedisMaster = null;

        try {

            jedisMaster = getJedis();

            jedisMaster.expire(key, seconds);

        } finally {

            returnResource(jedisMaster);

        }

    }

    public static boolean exists(String key) throws Exception{

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        try {

            jedisMaster = getJedis();

            return jedisMaster.exists(key);

        } finally {

            returnResource(jedisMaster);

        }

    }

    

    public static Long hset(String key,String entryKey,String entryValue) throws Exception{

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        try {

            jedisMaster = getJedis();

            return jedisMaster.hset(key, entryKey, entryValue);

        } finally {

            returnResource(jedisMaster);

        }

    }

    

    public static String hget(String key,String file) throws Exception {

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        String value = null;

        try {

            jedisMaster = getJedis();

            value = jedisMaster.hget(key,file);

        } finally {

            returnResource(jedisMaster);

        }

        return value;

    }

    

    public static Long hlen(String key)throws Exception {

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        Long value = 0L;

        try {

            jedisMaster = getJedis();

            value = jedisMaster.hlen(key);

        } finally {

            returnResource(jedisMaster);

        }

        return value;

    }

    

}

     JedisDataClient

        package com.arec.jedisclient;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.LinkedHashSet;

import java.util.List;

import java.util.Map;

import java.util.Properties;

import java.util.Set;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;

import redis.clients.jedis.JedisPoolConfig;

public class JedisDataClient {

    private static JedisPool poolMaster;

//    private static JedisPool poolSlave;

//    private static String password = "";

    // public static final String VALUE_TYPE_STRING = "string";

    // public static final String VALUE_TYPE_LIST = "list";

    // public static final String VALUE_TYPE_MAP = "map";

//    private static String filePath;

    private JedisDataClient() {

    }

    private static Logger log = LoggerFactory.getLogger(JedisDataClient.class);

    static {

            try {

                Properties p = new Properties();

                ClassLoader classloader = Thread.currentThread().getContextClassLoader();

                InputStream is = classloader.getResourceAsStream("/redisConfig.properties");

                p.load(is);

                String redisHostMaster = p.getProperty("redisHostMaster").trim();

                // password = p.getProperty("password");

                int redisPort = Integer.parseInt(p.getProperty("redisPort").trim());

                int timeout = Integer.parseInt(p.getProperty("timeout").trim());

//                redisHostMaster = "192.168.1.163";

//                redisPort = 6379;

//                timeout = 9000;

                JedisPoolConfig configMaster = new JedisPoolConfig();

                configMaster.setMaxTotal(30000);// 设置最大连接数

                configMaster.setMaxIdle(100); // 设置最大空闲数

                configMaster.setMinIdle(10);

                configMaster.setMaxWaitMillis(10000);// 设置超时时间

                configMaster.setTestWhileIdle(true);

                configMaster.setTestOnBorrow(false);

                poolMaster = new JedisPool(configMaster, redisHostMaster,redisPort, timeout);

                log.info(">>>>>>>>>redisData ip:" + redisHostMaster);

                log.info(">>>>>>>>>redisData port:"+redisPort);

                log.info(">>>>>>>>>redisData timeout:"+timeout);

                log.info(">>>>>>>>>数据管理redis master连接池初始化成功...");

            } catch (Exception e) {

                log.info(">>>>>>>>>数据管理redis master连接池初始化失败,系统无法正常使用!!!");

                e.printStackTrace();

            }

    }

    /*private synchronized static JedisPool initSlavePool() throws Exception {

        if (null == poolSlave) {

            String redisHostSlave = null;

            try {

                Properties p = new Properties();

                ClassLoader classloader = Thread.currentThread().getContextClassLoader();

                InputStream is = classloader.getResourceAsStream("/redisConfig.properties");

                p.load(is);

                redisHostSlave = p.getProperty("redisHostSlave").trim();

                // password = p.getProperty("password");

                redisPort = Integer.parseInt(p.getProperty("redisPort").trim());

                timeout = Integer.parseInt(p.getProperty("timeout").trim());

                JedisPoolConfig configSlave = new JedisPoolConfig();

                configSlave.setMaxTotal(30000);// 设置最大连接数

                configSlave.setMaxIdle(6000); // 设置最大空闲数

                configSlave.setMaxWaitMillis(10000);// 设置超时时间

                configSlave.setTestWhileIdle(true);

                configSlave.setTestOnBorrow(false);

                poolSlave = new JedisPool(configSlave, redisHostSlave,

                        redisPort, timeout);

            } catch (Exception e) {

                throw e;

            }

        }

        return poolSlave;

    }*/

    private static Jedis getMasterJedis() throws Exception {

            return poolMaster.getResource();

    }

    

    /*private synchronized static Jedis getSlaveJedis() throws Exception {

        if (poolSlave == null) {

            initSlavePool();

        }

        Jedis jedis = null;

        if (poolSlave != null) {

            jedis = poolSlave.getResource();

        }

        return jedis;

    }*/

    private static void returnResource(Jedis jedis) {

        if (jedis != null) {

            jedis.disconnect();

            poolMaster.returnResourceObject(jedis);

        }

    }

    /**

     * 向redis加入数据

     *

     * @param key

     * @param value

     * @throws Exception

     */

    public static void set(String key, String value) throws Exception {

        Jedis jedisMaster = null;

        try {

            jedisMaster = getMasterJedis();

            jedisMaster.set(key, value);

        } finally {

            returnResource(jedisMaster);

        }

    }

    /**

     * 向redis加入String类型数据,并设置保存时间

     *

     * @param key

     * @param value

     * @param seconds

     *            数据保存时间(单位:秒)

     * @throws Exception

     */

    public static void set(String key, String value, int seconds)

            throws Exception {

        Jedis jedisMaster = null;

        try {

            jedisMaster = getMasterJedis();

            jedisMaster.set(key, value);

            jedisMaster.expire(key, seconds);

            

        } finally {

            returnResource(jedisMaster);

        }

    }

    /**

     * 从redis取值

     *

     * @param key

     * @return

     * @throws Exception

     */

    public static String get(String key) throws Exception {

        if (null == key || "".equals(key.trim())) {

            return null;

        }

        Jedis jedisMaster = null;

        Jedis jedisSlave = null;

        String value = null;

        try {

//            jedisSlave = getSlaveJedis();

//            value = jedisSlave.get(key);

            jedisMaster = getMasterJedis();

            value = jedisMaster.get(key);

        } catch (Exception e) {

//            jedisMaster = getMasterJedis();

//            value = jedisMaster.get(key);

            throw e;

        } finally {

            try {

                returnResource(jedisMaster);

            } catch (Exception e) {

                throw e;

            }

//            try {

//                returnResource(jedisSlave,jedisSlave);

//            } catch (Exception e) {

//                throw e;

//            }

        }

        return value;

    }

    public static long del(String key) throws Exception {

        if (null == key || "".equals(key.trim())) {

            return 0;

        }

        long value = 0;

        try {

            Jedis jedisMaster = getMasterJedis();

            value = jedisMaster.del(key);

        } catch (Exception e) {

            throw e;

        }

        return value;

    }

    

    public static List<String> hmget(String key,String... files) throws Exception {

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        List<String> list = null;

        try {

            jedisMaster = getMasterJedis();

            list = jedisMaster.hmget(key,files);

        } finally {

            returnResource(jedisMaster);

        }

        return list;

    }

    

    public static void hmset(String key,Map<String,String> map,Integer seconds) throws Exception {

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        try {

            jedisMaster = getMasterJedis();

            jedisMaster.hmset(key, map);

            if(null != seconds && seconds > 0){

                jedisMaster.expire(key, seconds);                

            }

        } finally {

            returnResource(jedisMaster);

        }

    }

    

    public static void hset(String key,String mapKey,String mapValue,Integer seconds) throws Exception {

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        try {

            jedisMaster = getMasterJedis();

            jedisMaster.hset(key, mapKey,mapValue);

            if(null != seconds && seconds > 0){

                jedisMaster.expire(key, seconds);                

            }

        } finally {

            returnResource(jedisMaster);

        }

    }

    

    /**

     * <p>Title:JedisSessionClient.java</p>

     * <p>Description:续期</p>

     * @param key

     * @param seconds

     * @throws Exception

     */

    public static void expire(Strin
b4fa
g key, int seconds)

            throws Exception {

        if(null == key || "".equals(key.trim())){

            return;

        }

        Jedis jedisMaster = null;

        try {

            jedisMaster = getMasterJedis();

            jedisMaster.expire(key, seconds);

        } finally {

            returnResource(jedisMaster);

        }

    }

    

    /**

     * <p>Title:JedisDataClient.java</p>

     * <p>Description:向List尾部加入数据,放入缓存,如果key不存在,创建该对象</p>

     * <p>Company:上海艾立可金融信息服务有限公司</p>

     * @author hank

     * @date 2015年10月20日 上午10:27:02

     * @param key

     * @param value

     * @throws Exception

     */

    public static void setList(String key,List<String> list,int...times) throws Exception{

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        try {

            jedisMaster = getMasterJedis();

            if(null != list && list.size() > 0){

                jedisMaster.rpush(key, list.toArray(new String[list.size()]));

                if(null == times || times.length == 0){

                    expire(key, (int)TimeUnit.MINUTES.toSeconds(30));

                } else {

                    expire(key, times[0]);

                }

                log.debug(">>>>>>>>>>>list key=" + key);

            }

        } finally {

            returnResource(jedisMaster);

        }

    }

    

    /**

     *

     * <p>Title:JedisDataClient.java</p>

     * <p>Description:向list加入数据放入缓存,并保持list中的数据不重复</p>

     * <p>Company:上海艾立可金融信息服务有限公司</p>

     * @author hank

     * @date 2015年10月23日 上午9:44:37

     * @param key

     * @param list

     * @param times

     * @throws Exception

     */

    public static void setUniqueList(String key,List<String> list,int...times) throws Exception{

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        try {

            jedisMaster = getMasterJedis();

            if(null != list && list.size() > 0){

                Set<String> set = new LinkedHashSet<String>();

                set.addAll(list);

                List<String> oldList = jedisMaster.lrange(key, 0, -1);

                set.addAll(oldList);

                set.addAll(list);

                list = new ArrayList<String>(set);

                jedisMaster.del(key);

                jedisMaster.rpush(key, list.toArray(new String[list.size()]));

                if(null == times || times.length == 0){

                    expire(key, (int)TimeUnit.MINUTES.toSeconds(30));

                } else {

                    expire(key, times[0]);

                }

                log.info(">>>>>>>>>>>list key=" + key);

            }

        } finally {

            returnResource(jedisMaster);

        }

    }

    

    /**

     * <p>Title:JedisDataClient.java</p>

     * <p>Description:取出list中的数据,start从0开始,end=-1表示全部取出</p>

     * @param key

     * @param start

     * @param end

     * @return

     * @throws Exception

     */

    public static List<String> getList(String key,long start, long end) throws Exception{

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        List<String> list = null;

        try {

            jedisMaster = getMasterJedis();

            list = jedisMaster.lrange(key, start, end);

        } finally {

            returnResource(jedisMaster);

        }

        return list;

    }

    

    /**

     *

     * <p>Title:JedisDataClient.java</p>

     * <p>Description:删除指定值的元素</p>

     * @param key

     * @param values

     * @throws Exception

     */

    public synchronized static void delListItem(String key,String...values) throws Exception{

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        List<String> list = null;

        try {

            jedisMaster = getMasterJedis();

            list = jedisMaster.lrange(key, 0, -1);

            if((null != list && list.size() > 0)

                    && (null != values && values.length > 0)){

                for(int j = 0; j < values.length; j++){

                    for(int i = 0; i < list.size(); i++){

                        if(values[j].equals(list.get(i))){

                            list.remove(i);

                            break;

                        }

                    }

                }

                jedisMaster.del(key);

                if(list.size() > 0){

                    jedisMaster.rpush(key, list.toArray(new String[list.size()]));

                }

            }

        } finally {

            returnResource(jedisMaster);

        }

    }

    

    /**

     * <p>Title:JedisDataClient.java</p>

     * <p>Description:取出map所有的key</p>

     * @param key

     * @return

     * @throws Exception

     */

    public static List<String> hkeys(String key) throws Exception{

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        List<String> list = null;

        try {

            jedisMaster = getMasterJedis();

            Set<String> set = jedisMaster.hkeys(key);

            if(null != set && set.size() > 0){

                return new ArrayList<String>(set);

            }

        } finally {

            returnResource(jedisMaster);

        }

        return list;

    }

    

    /**

     * <p>Title:JedisDataClient.java</p>

     * <p>Description:取出map所有的value</p>

     * @param key

     * @return

     * @throws Exception

     */

    public static List<String> hvals(String key) throws Exception{

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        List<String> list = null;

        try {

            jedisMaster = getMasterJedis();

            list = jedisMaster.hvals(key);

        } finally {

            returnResource(jedisMaster);

        }

        return list;

    }

    

    /**

     * <p>Title:JedisDataClient.java</p>

     * <p>Description:判断是否存在</p>

     * @param key

     * @return

     * @throws Exception

     */

    public static boolean exists(String key) throws Exception{

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        try {

            jedisMaster = getMasterJedis();

            return jedisMaster.exists(key);

        } finally {

            returnResource(jedisMaster);

        }

    }

    

    public static Long hdel(String key,String...fields) throws Exception{

        if (null == key || "".equals(key.trim())) {

            throw new Exception("the key can not be null.");

        }

        Jedis jedisMaster = null;

        try {

            jedisMaster = getMasterJedis();

            return jedisMaster.hdel(key, fields);

        } finally {

            returnResource(jedisMaster);

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: