设为首页 收藏本站
查看: 833|回复: 0

[经验分享] redis的使用:获取redis实例的工具类

[复制链接]

尚未签到

发表于 2015-7-21 09:48:09 | 显示全部楼层 |阅读模式
  package com.wanhua.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import play.Play;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* Redis工具类,用于获取RedisPool. 参考官网说明如下: You shouldn't use the same instance from different threads because you'll have strange errors. And sometimes creating lots of Jedis instances is not good enough because it means lots of sockets and connections, which leads to strange errors as well. A single Jedis instance is not threadsafe! To avoid these problems, you should use JedisPool, which is a threadsafe pool of network connections. This way you can overcome those strange errors and achieve great performance. To use it, init a pool: JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost"); You can store the pool somewhere statically, it is thread-safe. JedisPoolConfig includes a number of helpful Redis-specific connection pooling defaults. For example, Jedis with JedisPoolConfig will close a connection after 300 seconds if it has not been returned.
*
* @author bqwang
*/
public class JedisUtil {
    private static Logger logger = Logger.getLogger(JedisUtil.class.getName()); // logger
    /**
     * 私有构造器.
     */
    private JedisUtil() {
    }
    private static Map maps = new HashMap();
    /**
     * 获取连接池.
     *
     * @return 连接池实例
     */
    private static JedisPool getPool(String ip, int port) {
        String key = ip + ":" + port;
        JedisPool pool = null;
        if (!maps.containsKey(key)) {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxIdle(Integer.parseInt(Play.configuration.getProperty("redis.pool.maxIdle")));
            config.setMaxTotal(Integer.parseInt(Play.configuration.getProperty("redis.pool.maxTotal")));
            config.setTestOnBorrow(Play.configuration.getProperty("redis.pool.testOnBorrow") == "true" ? true : false);
            config.setTestOnReturn(Play.configuration.getProperty("redis.pool.testOnReturn") == "true" ? true : false);
            try {
                /**
                 * 如果你遇到 java.net.SocketTimeoutException: Read timed out exception的异常信息 请尝试在构造JedisPool的时候设置自己的超时值. JedisPool默认的超时时间是2秒(单位毫秒)
                 */
                pool = new JedisPool(config, ip, port, Integer.parseInt(Play.configuration.getProperty("redis.pool.timeout")));
                maps.put(key, pool);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            pool = maps.get(key);
        }
        return pool;
    }
    /**
     * 类级的内部类,也就是静态的成员式内部类,该内部类的实例与外部类的实例 没有绑定关系,而且只有被调用到时才会装载,从而实现了延迟加载。
     */
    private static class RedisUtilHolder {
        /**
         * 静态初始化器,由JVM来保证线程安全
         */
        private static JedisUtil instance = new JedisUtil();
    }
    /**
     * 当getInstance方法第一次被调用的时候,它第一次读取 RedisUtilHolder.instance,导致RedisUtilHolder类得到初始化;而这个类在装载并被初始化的时候,会初始化它的静 态域,从而创建RedisUtil的实例,由于是静态的域,因此只会在虚拟机装载类的时候初始化一次,并由虚拟机来保证它的线程安全性。 这个模式的优势在于,getInstance方法并没有被同步,并且只是执行一个域的访问,因此延迟初始化并没有增加任何访问成本。
     */
    public static JedisUtil getInstance() {
        return RedisUtilHolder.instance;
    }
    /**
     * 获取Redis实例.
     *
     * @return Redis工具类实例
     */
    public Jedis getJedis() {
        // logger.info("get getJedis------");
        Jedis jedis = null;
        int count = 0;
        do {
            String ip = Play.configuration.getProperty("redis.server.ip");
            // logger.info("get ip------"+ip);
            int port = Integer.parseInt(Play.configuration.getProperty("redis.server.port"));
            // logger.info("get port------"+port);
            try {
                jedis = getPool(ip, port).getResource();
            } catch (Exception e) {
                logger.info("get redis master1 failed!" + e);
                // 销毁对象
                getPool(ip, port).returnBrokenResource(jedis);
            }
            count++;
        } while (jedis == null && count < Integer.parseInt(Play.configuration.getProperty("redis.pool.retryTimes")));
        // logger.info("get jedis success------");
        return jedis;
    }
    /**
     * 释放redis实例到连接池.
     *
     * @param jedis
     *            redis实例
     */
    public static void closeJedis(Jedis jedis) {
        String ip = Play.configuration.getProperty("redis.server.ip");
        int port = Integer.parseInt(Play.configuration.getProperty("redis.server.port"));
        if (jedis != null) {
            getPool(ip, port).returnResource(jedis);
        }
    }
    public static void main(String args[]) {
        Jedis jds = JedisUtil.getInstance().getJedis();
        // 向redis中添加数据
        jds.sadd("mb", "test");
        // 从redis中取数据
        Set resultSet = jds.smembers("mb");
        System.out.println("--get--result--from--redis---" + resultSet.toString());
        // 清空redis中指定key的消息
        jds.del("mb");
        // 清空所有redis中消息
        jds.flushDB();
    }
}

  在配置文件中添加以下配置:
  redis.pool.maxIdle=200
redis.pool.maxTotal=100
redis.pool.timeout=30000
redis.pool.retryTimes=5
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true
redis.server.ip = 10.10.103.208
redis.server.port = 6378

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-88954-1-1.html 上篇帖子: 初识redis 下篇帖子: Redis新的存储模式diskstore
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表