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

[经验分享] Redis

[复制链接]

尚未签到

发表于 2016-12-20 11:42:33 | 显示全部楼层 |阅读模式
  package com.commons.redis.cache;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

public class RedisManager {
    /** 切片链接池 */
    private static ShardedJedisPool shardedJedisPool;
    private ShardedJedis shardedJedis;

    // 设置与缓存服务器的连接池
    static {
        // 池基本配置
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxActive(Integer.parseInt(Config
                .getProperty("redis.pool.maxActive")));
        config.setMaxIdle(Integer.parseInt(Config
                .getProperty("redis.pool.maxIdle")));
        config.setMaxWait(Integer.parseInt(Config
                .getProperty("redis.pool.maxWait")));
        config.setTestOnBorrow(true);

        List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
        // 服务器列表
        String[] addressArr = (Config.getProperty("redis.address")).split(",");
        for (String str : addressArr) {
            String []addressConfig = str.split(":");
            shards.add(new JedisShardInfo(addressConfig[0], Integer
                    .parseInt(addressConfig[1]), addressConfig[2]));
        }
        // 构造池
        shardedJedisPool = new ShardedJedisPool(config, shards);
    }

    /**
     * redis的List集合 ,向key这个list添加元素
     *
     * @param key
     *            List别名
     * @param string
     *            元素
     * @return
     */
    public long rpush(String key, String string) {
        try {
            shardedJedis = shardedJedisPool.getResource();
            long ret = shardedJedis.rpush(key, string);
            shardedJedisPool.returnResource(shardedJedis);
            return ret;
        } catch (Exception e) {
            if (shardedJedis != null)
                shardedJedisPool.returnBrokenResource(shardedJedis);
            e.printStackTrace();
            return 0L;
        }
    }

    /**
     * 获取key这个List,从第几个元素到第几个元素 LRANGE key start
     * stop返回列表key中指定区间内的元素,区间以偏移量start和stop指定。
     * 下标(index)参数start和stop都以0为底,也就是说,以0表示列表的第一个元素,以1表示列表的第二个元素,以此类推。
     * 也可以使用负数下标,以-1表示列表的最后一个元素,-2表示列表的倒数第二个元素,以此类推。
     *
     * @param key
     *            List别名
     * @param start
     *            开始下标
     * @param end
     *            结束下标
     * @return
     */
    public List<String> lrange(String key, long start, long end) {
        try {
            shardedJedis = shardedJedisPool.getResource();
            List<String> ret = shardedJedis.lrange(key, start, end);
            shardedJedisPool.returnResource(shardedJedis);
            return ret;
        } catch (Exception e) {
            if (shardedJedis != null)
                shardedJedisPool.returnBrokenResource(shardedJedis);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将哈希表key中的域field的值设为value。
     *
     * @param key
     *            哈希表别名
     * @param field键
     * @param value
     *            值
     */
    public void hset(String key, String field, String value) {
        try {
            shardedJedis = shardedJedisPool.getResource();
            shardedJedis.hset(key, field, value);
            shardedJedisPool.returnResource(shardedJedis);
        } catch (Exception e) {
            if (shardedJedis != null)
                shardedJedisPool.returnBrokenResource(shardedJedis);
            e.printStackTrace();
        }
    }

    /**
     * 向key赋值
     *
     * @param key
     * @param value
     */
    public void set(String key, String value) {
        try {
            shardedJedis = shardedJedisPool.getResource();
            shardedJedis.set(key, value);
            shardedJedisPool.returnResource(shardedJedis);
        } catch (Exception e) {
            if (shardedJedis != null)
                shardedJedisPool.returnBrokenResource(shardedJedis);
            e.printStackTrace();
        }
    }

    /**
     * 获取key的值
     *
     * @param key
     * @return
     */
    public String get(String key) {
        try {
            shardedJedis = shardedJedisPool.getResource();
            String value = shardedJedis.get(key);
            shardedJedisPool.returnResource(shardedJedis);
            return value;
        } catch (Exception e) {
            if (shardedJedis != null)
                shardedJedisPool.returnBrokenResource(shardedJedis);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将多个field - value(域-值)对设置到哈希表key中。
     *
     * @param key
     * @param map
     */
    public void hmset(String key, Map<String, String> map) {
        try {
            shardedJedis = shardedJedisPool.getResource();
            shardedJedis.hmset(key, map);
            shardedJedisPool.returnResource(shardedJedis);
        } catch (Exception e) {
            if (shardedJedis != null)
                shardedJedisPool.returnBrokenResource(shardedJedis);
            e.printStackTrace();
        }
    }

    /**
     * 给key赋值,并生命周期设置为seconds
     *
     * @param key
     * @param seconds
     *            生命周期 秒为单位
     * @param value
     */
    public void setex(String key, int seconds, String value) {
        try {
            shardedJedis = shardedJedisPool.getResource();
            shardedJedis.setex(key, seconds, value);
            shardedJedisPool.returnResource(shardedJedis);
        } catch (Exception e) {
            if (shardedJedis != null)
                shardedJedisPool.returnBrokenResource(shardedJedis);
            e.printStackTrace();
        }
    }

    /**
     * 为给定key设置生命周期
     *
     * @param key
     * @param seconds
     *            生命周期 秒为单位
     */
    public void expire(String key, int seconds) {
        try {
            shardedJedis = shardedJedisPool.getResource();
            shardedJedis.expire(key, seconds);
            shardedJedisPool.returnResource(shardedJedis);
        } catch (Exception e) {
            if (shardedJedis != null)
                shardedJedisPool.returnBrokenResource(shardedJedis);
            e.printStackTrace();
        }
    }

    /**
     * 检查key是否存在
     *
     * @param key
     * @return
     */
    public boolean exists(String key) {
        try {
            shardedJedis = shardedJedisPool.getResource();
            boolean bool = shardedJedis.exists(key);
            shardedJedisPool.returnResource(shardedJedis);
            return bool;
        } catch (Exception e) {
            if (shardedJedis != null) {
                shardedJedisPool.returnBrokenResource(shardedJedis);
            }
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 返回key值的类型 none(key不存在),string(字符串),list(列表),set(集合),zset(有序集),hash(哈希表)
     *
     * @param key
     * @return
     */
    public String type(String key) {
        try {
            shardedJedis = shardedJedisPool.getResource();
            String type = shardedJedis.type(key);
            shardedJedisPool.returnResource(shardedJedis);
            return type;
        } catch (Exception e) {
            if (shardedJedis != null) {
                shardedJedisPool.returnBrokenResource(shardedJedis);
            }
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从哈希表key中获取field的value
     *
     * @param key
     * @param field
     */
    public String hget(String key, String field) {
        try {
            shardedJedis = shardedJedisPool.getResource();
            String value = shardedJedis.hget(key, field);
            shardedJedisPool.returnResource(shardedJedis);
            return value;
        } catch (Exception e) {
            if (shardedJedis != null) {
                shardedJedisPool.returnBrokenResource(shardedJedis);
            }
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 返回哈希表key中,所有的域和值
     *
     * @param key
     * @return
     */
    public Map<String, String> hgetAll(String key) {
        try {
            shardedJedis = shardedJedisPool.getResource();
            Map<String, String> map = shardedJedis.hgetAll(key);
            shardedJedisPool.returnResource(shardedJedis);
            return map;
        } catch (Exception e) {
            if (shardedJedis != null) {
                shardedJedisPool.returnBrokenResource(shardedJedis);
            }
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 返回哈希表key中,所有的域和值
     *
     * @param key
     * @return
     */
    public Set<?> smembers(String key) {
        try {
            shardedJedis = shardedJedisPool.getResource();
            Set<?> set = shardedJedis.smembers(key);
            shardedJedisPool.returnResource(shardedJedis);
            return set;
        } catch (Exception e) {
            if (shardedJedis != null) {
                shardedJedisPool.returnBrokenResource(shardedJedis);
            }
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 移除集合中的member元素
     *
     * @param key
     *            List别名
     * @param field
     *            键
     */
    public void delSetObj(String key, String field) {
        try {
            shardedJedis = shardedJedisPool.getResource();
            shardedJedis.srem(key, field);
            shardedJedisPool.returnResource(shardedJedis);
        } catch (Exception e) {
            if (shardedJedis != null) {
                shardedJedisPool.returnBrokenResource(shardedJedis);
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断member元素是否是集合key的成员。是(true),否则(false)
     *
     * @param key
     * @param field
     * @return
     */
    public boolean isNotField(String key, String field) {
        try {
            shardedJedis = shardedJedisPool.getResource();
            boolean bool = shardedJedis.sismember(key, field);
            shardedJedisPool.returnResource(shardedJedis);
            return bool;
        } catch (Exception e) {
            if (shardedJedis != null) {
                shardedJedisPool.returnBrokenResource(shardedJedis);
            }
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 如果key已经存在并且是一个字符串,将value追加到key原来的值之后
     *
     * @param key
     * @param value
     */
    public void append(String key, String value) {
        try {
            shardedJedis = shardedJedisPool.getResource();
            shardedJedis.append(key, value);
            shardedJedisPool.returnResource(shardedJedis);
        } catch (Exception e) {
            if (shardedJedis != null) {
                shardedJedisPool.returnBrokenResource(shardedJedis);
            }
            e.printStackTrace();
        }
    }

    /**
     * 获取客户端连接
     *
     * @return
     */
    public static ShardedJedis getShardedJedis() {
        try {
            return shardedJedisPool.getResource();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 释放连接
     *
     * @param jedis
     */
    public static void returnResourceObject(ShardedJedisPool shardedJedisPool) {
        try {
            if (shardedJedisPool != null) {
                shardedJedisPool.returnResourceObject(shardedJedisPool);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 关闭 Redis
     */
    public void destory() {
        try {
            shardedJedisPool.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
  package com.commons.redis.cache;

import java.io.File;
import java.io.InputStream;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Config {
    private static Log log = LogFactory.getLog(Config.class);
    private static Properties props = new Properties();

    private static String contextAbsoultePath = "";
    private static String contextPath = "";
    private static ServletContext context;
    private static InitialContext ic;

    static {
        InputStream in = Config.class.getResourceAsStream("/commons-pool.properties");
        try {
            if (in != null) {
                try {
                    props.load(in);
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String getProperty(String key) {
        return getProperty(key, "");
    }

   
    public static String getProperty(String key,String defaultValue) {
        return props.getProperty(key, defaultValue);
    }


    public static String getPathProperty(String key) {
        String s = props.getProperty(key, "");
        s = s.replace('/', File.separator.charAt(0));
        return s;
    }


    public static String getContextAbsoultePath() {
        return contextAbsoultePath;
    }


    public static void setContextAbsoultePath(String contextAbsoultePath) {
        Config.contextAbsoultePath = contextAbsoultePath;
    }


    public static String getContextPath() {
        return contextPath;
    }


    public static void setContextPath(String contextPath) {
        Config.contextPath = contextPath;
    }

    public static void setContext(ServletContext ctx) {
        context = ctx;
    }

    public static ServletContext getContext() {
        return context;
    }

    public static InitialContext getInitialContext() {
        try {
            if (ic == null) {
                Properties p = new Properties();
                p.put(
                    Context.INITIAL_CONTEXT_FACTORY,
                    getProperty("jndi.InitialContextFactory"));
                p.put(Context.PROVIDER_URL, getProperty("jndi.ProviderURL"));

                ic = new InitialContext(p);
            }
        } catch (Exception ne) {
            log.fatal(ne);
        }

        return ic;
    }
}
  commons-pool.properties:
  #最大分配的对象数 
redis.pool.maxActive=5000

#最大能够保持idel状态的对象数 
redis.pool.maxIdle=5000

#当池内没有返回对象时,最大等待时间 
redis.pool.maxWait=10000

#当调用borrow Object方法时,是否进行有效性检查 
redis.pool.testOnBorrow=true
 
#当调用return Object方法时,是否进行有效性检查 
redis.pool.testOnReturn=true


#address[ip地址:端口号:密码]多个以英文逗号分开
redis.address=127.0.0.1:6379:rayping88

package com.commons.redis.cache;

public class RedisTest {
    public static void main(String[] args) {
        RedisManager redisManager =new RedisManager();
        redisManager.set("ray", "redis 测试");
        System.out.println(redisManager.get("ray"));
    }

}

运维网声明 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-316972-1-1.html 上篇帖子: redis官方文档中文翻译版地址 下篇帖子: understanding redis internal
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

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

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

扫描微信二维码查看详情

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


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


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


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



合作伙伴: 青云cloud

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