单机版 RedisPoolUtil({基本操作封装工具类})【一】

<!--集成的RedisJAR-->
<!--引入jedis需的jar包-->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
<!--Spring整合jedis的依赖-->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.7.1.RELEASE</version>
</dependency>
package com.dsj.gdbd.utils.jedis;

import com.dsj.gdbd.utils.serialize.SerializingUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class RedisPoolUtil implements InitializingBean {
    private static JedisPool pool = null;
    /**
     * 默认缓存时间
     */
    private static final int DEFAULT_CACHE_SECONDS = 0;// 单位秒 设置成一个钟
    private static Logger LOGGER = Logger.getLogger(RedisPoolUtil.class);

    public static JedisPool getPool() {
        return pool;
    }

    @PostConstruct
    public void init() {

        if (pool == null) {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(10000);
            config.setMaxIdle(1000);
            config.setMaxWaitMillis(1000 * 10);

            //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
            config.setTestOnBorrow(true);
            //new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);
            //pool = new JedisPool(config, "47.94.15.160", 6379, 10000, "[email protected]");
            pool = new JedisPool(config, "192.168.31.206", 6379, 10000);
        }
    }

    public synchronized static Jedis getResource() {
        if (pool == null) {
            pool = getPool();
        }
        return pool.getResource();
    }
    public static void closeRedis(Jedis redis) {
        if (redis != null) {
            redis.close();
        }
    }
    public static void set(String key, String value) {
        Jedis redis = getResource();
        try {
            redis.set(key, value);
        } finally {
            closeRedis(redis);
        }
    }

    public static void set(Object key, Object value) {
        Jedis redis = getResource();
        try {
            redis.set(SerializingUtil.serialize(key), SerializingUtil.serialize(value));
        } finally {
            closeRedis(redis);
        }
    }
    public static String get(String key) {
        Jedis redis = getResource();
        try {
            return redis.get(key);
        } finally {
            closeRedis(redis);
        }
    }

    /**
     * 根据缓存键获取Redis缓存中的值.<br/>
     *
     * @param key 键.<br/>
     * @return Object .<br/>
     * @throws Exception
     */
    public static Object get(Object key) {
        Jedis jedis = null;
        try {
            jedis = getResource();
            byte[] obj = jedis.get(SerializingUtil.serialize(key));
            return obj == null ? null : SerializingUtil.deserialize(obj);
        } catch (Exception e) {
            LOGGER.error("Cache获取失败:" + e);
            return null;
        } finally {
            closeRedis(jedis);
        }
    }
    /**
     * 根据缓存键获取Redis缓存中的值.<br/>
     *
     * @param key 键.<br/>
     * @return Object .<br/>
     * @throws Exception
     */
    public static Object getObj(String key) {
        Jedis jedis = null;
        try {
            jedis = getResource();
            byte[] obj = jedis.get(SerializingUtil.serialize(key));
            return obj == null ? null : SerializingUtil.deserialize(obj);
        } catch (Exception e) {
            LOGGER.error("Cache获取失败:" + e);
            return null;
        } finally {
            closeRedis(jedis);
        }
    }
    /**
     * 根据缓存键获取Redis缓存中的值.<br/>
     *
     * @param key 键.<br/>
     * @return Object .<br/>
     * @throws Exception
     */
    public static String getStr(String key) {
        Jedis jedis = null;
        try {
            jedis = getResource();
            return jedis.get(key);

        } catch (Exception e) {
            LOGGER.error("Cache获取失败:" + e);
            return null;
        } finally {
            closeRedis(jedis);
        }
    }

    /**
     * 根据缓存键获取Redis缓存中的值.<br/>
     *
     * @param key 键.<br/>
     * @return Object .<br/>
     * @throws Exception
     */
    public static byte[] get(byte[] obj) {
        Jedis jedis = null;
        try {
            jedis = getResource();
            return jedis.get(obj);
        } catch (Exception e) {
            LOGGER.error("Cache获取失败:" + e);
            return null;
        } finally {
            closeRedis(jedis);
        }
    }

    /**
     * 判断一个key是否存在
     *
     * @param key
     * @return
     */
    public static Boolean exists(Object key) {
        Jedis jedis = null;
        Boolean result = false;
        try {
            jedis = getResource();
            return jedis.exists(SerializingUtil.serialize(key));
        } catch (Exception e) {
            LOGGER.error("Cache获取失败:" + e);
            return false;
        } finally {
            closeRedis(jedis);
        }
    }

    public static Boolean existsKey(String key) {
        Jedis jedis = null;
        Boolean result = false;
        try {
            jedis = getResource();
            return jedis.exists(key);
        } catch (Exception e) {
            LOGGER.error("Cache获取失败:" + e);
            return false;
        } finally {
            closeRedis(jedis);
        }
    }

    /**
     * 根据缓存键清除Redis缓存中的值.<br/>
     *
     * @param keys
     * @return
     * @throws Exception
     */
    public static Boolean del(Object... keys) {
        Jedis jedis = null;
        try {
            jedis = getResource();
            jedis.del(SerializingUtil.serialize(keys));
            return true;
        } catch (Exception e) {
            LOGGER.error("Cache删除失败:" + e);
            return false;
        } finally {
            closeRedis(jedis);
        }
    }

    /**
     * 根据缓存键清除Redis缓存中的值.<br/>
     *
     * @param keys
     * @return
     * @throws Exception
     */
    public static Long del(String... keys) {
        Jedis jedis = null;
        try {
            jedis = getResource();
            jedis.del(keys);
            return jedis.del(keys);
        } catch (Exception e) {
            LOGGER.error("Cache删除失败:" + e);
            return 0l;
        } finally {
            closeRedis(jedis);
        }
    }

    /**
     * 保存一个对象到Redis中(缓存过期时间:使用此工具类中的默认时间) . <br/>
     *
     * @param key    键 . <br/>
     * @param object 缓存对象 . <br/>
     * @return true or false . <br/>
     * @throws Exception
     */
    public static Boolean save(Object key, Object object) {
        return save(key, object, DEFAULT_CACHE_SECONDS);
    }

    /**
     * 保存一个对象到redis中并指定过期时间
     *
     * @param key     键 . <br/>
     * @param object  缓存对象 . <br/>
     * @param seconds 过期时间(单位为秒).<br/>
     * @return true or false .
     */
    public static Boolean save(Object key, Object object, int seconds) {
        Jedis jedis = null;
        try {
            jedis = getResource();
            jedis.set(SerializingUtil.serialize(key), SerializingUtil.serialize(object));
            jedis.expire(SerializingUtil.serialize(key), seconds);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("Cache保存失败:" + e);
            return false;
        } finally {
            closeRedis(jedis);
        }
    }
    /**
     * 删除Redis中的所有key
     *
     * @throws Exception
     */
    public static void flushAll() {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            jedis.flushAll();
        } catch (Exception e) {
            LOGGER.error("Cache清空失败:" + e);
        } finally {
            closeRedis(jedis);
        }
    }
    /**
     * 获取list
     *
     * @param <T>
     * @param key
     * @return list
     */
    public static <T> Map<String, T> getMap(String key) throws Exception {
        if (getResource() == null || !getResource().exists(key.getBytes())) {
            return null;
        }
        byte[] in = getResource().get(key.getBytes());
        return (Map<String, T>) SerializingUtil.deserialize(in);
    }
    /**
     * 设置 map
     *
     * @param <T>
     * @param key
     */
    public static <T> void setMap(String key, Map<String, T> map) {
        try {
            getResource().set(key.getBytes(), SerializingUtil.serialize(map));
        } catch (Exception e) {
            LOGGER.warn("Set key error : " + e);
        }
    }
    public static Long dbSize() {
        Jedis jedis = null;
        Long size = 0l;
        try {
            jedis = pool.getResource();
            size = jedis.dbSize();
        } catch (Exception e) {
            LOGGER.error("查询库异常:" + e);
        } finally {
            closeRedis(jedis);
        }
        return size;
    }

    public static Set<String> keys(String pattern) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            Set<String> allKey = jedis.keys("*" + pattern + "*");
            return allKey;
        } catch (Exception e) {
            LOGGER.error("Cache获取失败:" + e);
            return new HashSet<String>();
        } finally {
            closeRedis(jedis);
        }
    }

    public static void flushDB() {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            jedis.flushDB();
        } catch (Exception e) {
            LOGGER.error("Cache清空失败:" + e);
        } finally {
            closeRedis(jedis);
        }
    }

    public static boolean setex(byte[] key, byte[] value, int expire) {
        Jedis redis = getResource();
        try {
            redis.setex(key, expire, value);
            return true;
        } catch (Exception e) {
            LOGGER.error("保存redis:" + e);
            return false;
        } finally {
            closeRedis(redis);
        }
    }

    public static boolean setex(String key, String value, int expire) {
        Jedis redis = getResource();
        try {
            redis.setex(key, expire, value);
            return true;
        } catch (Exception e) {
            LOGGER.error("保存redis:" + e);
            return false;
        } finally {
            closeRedis(redis);
        }
    }
    public static boolean setByte(byte[] key, byte[] value) {
        Jedis redis = getResource();
        try {
            redis.set(key, value);
            return true;
        } catch (Exception e) {
            LOGGER.error("保存redis:" + e);
            return false;
        } finally {
            closeRedis(redis);
        }
    }
    public void afterPropertiesSet() throws Exception {
        // TODO Auto-generated method stub
    }
}

原文地址:https://www.cnblogs.com/mlq2017/p/10260131.html

时间: 2024-08-28 17:38:12

单机版 RedisPoolUtil({基本操作封装工具类})【一】的相关文章

单机版 RedisUtils({基本操作封装工具类})【三】

<!--集成的RedisJAR--> <!--引入jedis需的jar包--> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <!--Spring整合jedis的依赖--> <depen

iOS开发—音频的播放的简单介绍和封装工具类

iOS开发—音频的播放的简单介绍和封装工具类 一.音效的播放简单介绍 简单来说,音频可以分为2种 (1)音效 又称“短音频”,通常在程序中的播放时长为1~2秒 在应用程序中起到点缀效果,提升整体用户体验 (2)音乐 比如游戏中的“背景音乐”,一般播放时间较长 框架:播放音频需要用到AVFoundation.framework框架 二.音效的播放 1.获得音效文件的路径 NSURL *url = [[NSBundle mainBundle] URLForResource:@"m_03.wav&qu

JAVA之旅(五)——this,static,关键字,main函数,封装工具类,生成javadoc说明书,静态代码块

JAVA之旅(五)--this,static,关键字,main函数,封装工具类,生成javadoc说明书,静态代码块 周末收获颇多,继续学习 一.this关键字 用于区分局部变量和成员变量同名的情况 this的特点 this就代表本类对象 这在我们的set方法里面是有的 public void setName(String name) { this.name = name; } this代表他所在的函数对属对象的引用 现在我们这里有这么一个需求 //公共的 类 类名 public class H

Android地图应用新视界--mapbox的常用功能封装工具类

上一篇- Android地图应用新视界--mapbox的应用开发之初始集成篇-中介绍了全球应用的多平台地图框架mapbox在Android端的集成步骤, 以及Android的地图应用新视界--mapbox的应用开发之简单功能提取篇,如果要了解建议先看前两篇哦 此篇将延续上篇内容,主要提取常用功能封装工具类,可以直接当工具类使用 直接上干货 如下: public class MapBoxUtils { private MapboxMap mapboxMap; private Context con

JavaWeb之抓包之旅(三) :HttpClient封装工具类

谈到httpClient相信大家都不陌生,网上也有一大推别人总结的.HttpClient是Apache Jakarta Common下的子项目,用来提供高效的.最新的.功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议. 详细请参考文档:HttpClient 我们在对数据进行请求的时候经常使用. 前不久在做一个百度地图定位的(通过GPS判断你在某个学校,但是并不是每个学校地图上都有,而且如何确定范围呢?) 类似于饿了么,我一直在想它为什么能定位到具体的某个宿舍呢

dljd_011_jdbc再次封装工具类_把数据库的相关信息写到配置文件中,减低代码的耦合度

一.将连接数据库所需的相关信息写入到配置文件.通过读取配置文件来获取数据库的相关信息 package edu.aeon.aeonutils; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import

java mail 封装工具类使用

直接上代码 配置QQ邮箱的IMAP 进入qq电子邮件点击 设置->账户里开启 SMTP 服务(开启IMAP/SMTP服务) 注意:在启用QQ邮箱的14天之后才能开启此服务 创建Sendmail 类  导入这两个jar : public class Sendmail {private static final Log logger = LogFactory.getLog(Sendmail.class); public static Map<String,Object> sendTextMa

FMDB 二次封装工具类,让你快速学会封装,集成数据库

来源:StrivEver 链接:http://www.jianshu.com/p/4c77aee0b41c 上个版本为了增加用户体验,部分页面集成了离线缓存数据功能,于是就在项目里使用了数据库管理离线数据.下面交大家一步步学会使用FMDB,以及FMDB的二次封装,同事把我二次封装的数据库放出来,希望能够帮助大家快速学习,集成数据库功能吧. 一.首先看一下STDB文件结构   STDB文件结构 Table.h主要放一些Table的创建语句, 方便管理我的数据库各张表创建 DBDefine.h主要放

SharedPreferences封装工具类

package com.demo.utils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import android.content.Context; import android.content.SharedPreferences; public class SpUtils { /** * 保存在手机里面的文件名 */ p