zoukankan      html  css  js  c++  java
  • redis使用:Jedis工具

    基本操作导入包

    <dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.0.0</version>
    </dependency>

    使用连接池

    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    import redis.clients.jedis.JedisPoolConfig;
    
    public class RedisConfig {
    
        private static String IP = "localhost";//服务器IP地址
    
        private static int PORT = 6379;//端口
    
        private static String PASSWORD = null;//密码
    
        private static int TIMEOUT = 10000;//连接超时的时间
    
        private static JedisPool jedisPool = null;
    
        public static final int DEFAULT_DATABASE = 0;//数据库模式是16个数据库 0~15
    
        static {
    
            try {
    
                JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
                jedisPoolConfig.setMaxTotal(1024); //连接实例的最大连接数
                jedisPoolConfig.setMaxIdle(8);//控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
                //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException
                jedisPoolConfig.setMaxWaitMillis(100);
                // 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
                jedisPoolConfig.setTestOnBorrow(true);
    
                jedisPool = new JedisPool(jedisPoolConfig, IP, PORT, TIMEOUT,PASSWORD,DEFAULT_DATABASE);
    
            } catch (Exception e) {
                System.out.println("static  JedisPoolConfig  Exception.....");
                e.printStackTrace();
            }
    
        }
    
        public synchronized static Jedis getJedis() {
            try {
                if (jedisPool != null) {
                    Jedis resource = jedisPool.getResource();
    //resource.configSet("timeout", "5"); // 超时设置
    return resource; } else { return null; } } catch (Exception e) { e.printStackTrace(); return null; } } public static void returnResource(final Jedis jedis) { if(jedis != null) { jedisPool.returnResource(jedis); } } public static void close(final Jedis jedis) { if(jedis != null) { jedis.close(); } } }
    private static Jedis jedis = RedisConfig.getJedis();
    
        public static String get(String key){
            return jedis.get(key);
        }
    
        public static String set(String key,String value){
            return jedis.set(key, value);
        }
    
        // 时间单位是秒
        public String setex(String key, int seconds, String value) {
            return jedis.setex(key, seconds, value);
        }
    
        public Boolean exists(String key) {
            return jedis.exists(key);
        }
    
        // 设置key value,如果key已经存在则返回0
        public Long setnx(String key, String value) {
            return jedis.setnx(key, value);
        }
    
        // 追加值
        public Long append(String key, String str) {
            return jedis.append(key, str);
        }
    
        public Long del(String... keys) {
            return jedis.del(keys);
        }
    
        public Long expire(String key, int seconds) {
            Jedis jedis = getJedis();
            return jedis.expire(key, seconds);
        }
        
        private static Jedis jedis = RedisConfig.getJedis();
    
        /**
         * 通过key同时设置 hash的多个field
         */
        public String hmset(String key, Map<String, String> hash) {
            return jedis.hmset(key, hash);
        }
    
        /**
         * 通过key给field设置指定的值,如果key不存在,则先创建
         */
        public Long hset(String key, String field, String value) {
            return jedis.hset(key, field, value);
        }
    
        /**
         * 通过key 和 field 获取指定的 value
         */
        public String hget(String key, String failed) {
            return jedis.hget(key, failed);
        }
    
        /**
         * 通过key 和  多个 field 获取指定的 value,field不存在时,返回null
         */
        public List<String> hmget(String key, String... fields) {
            return jedis.hmget(key, fields);
        }
    
        /**
         * 通过key和field判断是否有指定的value存在
         */
        public Boolean hexists(String key, String field) {
            return jedis.hexists(key, field);
        }
    
        /**
         * 通过key返回field的数量
         */
        public Long hlen(String key) {
            return jedis.hlen(key);
        }
    
        /**
         * 通过key 删除指定的 field
         */
        public Long hdel(String key, String... fields) {
            return jedis.hdel(key, fields);
        }
    
        /**
         * 通过key返回所有的field
         *
         * @param key
         * @return
         */
        public Set<String> hkeys(String key) {
            return jedis.hkeys(key);
        }
    
        /**
         * 通过key返回所有和key有关的value
         */
        public List<String> hvals(String key) {
            return jedis.hvals(key);
        }
    
    
        /**
         * 通过key获取所有的field和value
         */
        public Map<String, String> hgetall(String key) {
            return jedis.hgetAll(key);
        }
     private static Jedis jedis = RedisConfig.getJedis();
    
        /**
         * 通过key向list头部添加字符串
         *
         * @param key
         * @param strs 可以是一个string 也可以是string数组
         * @return 返回list的value个数
         */
        public Long lpush(String key, String... strs) {
            return jedis.lpush(key, strs);
        }
    
        /**
         * 通过key向list尾部添加字符串
         *
         * @param key
         * @param strs 可以是一个string 也可以是string数组
         * @return 返回list的value个数
         */
        public Long rpush(String key, String... strs) {
            return jedis.rpush(key, strs);
        }
    
        /**
         * 通过key在list指定的位置之前或者之后 添加字符串元素
         *
         * @param key
         * @param where LIST_POSITION枚举类型
         * @param pivot list里面的value
         * @param value 添加的value
         * @return
         */
        public Long linsert(String key, BinaryClient.LIST_POSITION where,
                String pivot, String value) {
            return jedis.linsert(key, where, pivot, value);
        }
    
        /**
         * 通过key设置list指定下标位置的value
         * 如果下标超过list里面value的个数则报错
         *
         * @param key
         * @param index 从0开始
         * @param value
         * @return 成功返回OK
         */
        public String lset(String key, Long index, String value) {
            return jedis.lset(key, index, value);
        }
    
        /**
         * 通过key从对应的list中删除指定的count个 和 value相同的元素
         *
         * @param key
         * @param count 当count为0时删除全部
         * @param value
         * @return 返回被删除的个数
         */
        public Long lrem(String key, long count, String value) {
            return jedis.lrem(key, count, value);
        }
    
        /**
         * 通过key保留list中从strat下标开始到end下标结束的value值
         * @return 成功返回OK
         */
        public String ltrim(String key, long start, long end) {
            return jedis.ltrim(key, start, end);
        }
    
        /**
         * 通过key从list的头部删除一个value,并返回该value
         */
        public synchronized String lpop(String key) {
            return jedis.lpop(key);
        }
    
        /**
         * 通过key从list尾部删除一个value,并返回该元素
         */
        synchronized public String rpop(String key) {
            return jedis.rpop(key);
        }
    
        /**
         * 通过key从一个list的尾部删除一个value并添加到另一个list的头部,并返回该value
         * 如果第一个list为空或者不存在则返回null
         */
        public String rpoplpush(String srckey, String dstkey) {
            return jedis.rpoplpush(srckey, dstkey);
        }
    
        /**
         * 通过key获取list中指定下标位置的value
         *
         * @param key
         * @param index
         * @return 如果没有返回null
         */
        public String lindex(String key, long index) {
            return jedis.lindex(key, index);
        }
    
        /**
         * 通过key返回list的长度
         */
        public Long llen(String key) {
            return jedis.llen(key);
        }
    
        /**
         * 通过key获取list指定下标位置的value
         * 如果start 为 0 end 为 -1 则返回全部的list中的value
         * @return
         */
        public List<String> lrange(String key, long start, long end) {
            return jedis.lrange(key, start, end);
        }
    private static Jedis jedis = RedisConfig.getJedis();
    
        /**
         * 通过key向指定的set中添加value
         * @return 添加成功的个数
         */
        public Long sadd(String key, String... members) {
            return jedis.sadd(key, members);
        }
    
        /**
         * 通过key删除set中对应的value值
         * @return 删除的个数
         */
        public Long srem(String key, String... members) {
            return jedis.srem(key, members);
        }
    
        /**
         * 通过key随机删除一个set中的value并返回该值
         *
         * @param key
         * @return
         */
        public String spop(String key) {
            return jedis.spop(key);
        }
    
        /**
         * 通过key获取set中的差集
         * 以第一个set为标准
         *
         * @param keys 可以 是一个string 则返回set中所有的value 也可以是string数组
         * @return
         */
        public Set<String> sdiff(String... keys) {
            return jedis.sdiff(keys);
        }
    
        /**
         * 通过key获取set中的差集并存入到另一个key中
         * 以第一个set为标准
         *
         * @param dstkey 差集存入的key
         * @param keys   可以 是一个string 则返回set中所有的value 也可以是string数组
         * @return
         */
        public Long sdiffstore(String dstkey, String... keys) {
            return jedis.sdiffstore(dstkey, keys);
        }
    
        /**
         * 通过key获取指定set中的交集
         *
         * @param keys 可以 是一个string 也可以是一个string数组
         * @return
         */
        public Set<String> sinter(String... keys) {
            return jedis.sinter(keys);
        }
    
        /**
         * 通过key获取指定set中的交集 并将结果存入新的set中
         *
         * @param dstkey
         * @param keys   可以 是一个string 也可以是一个string数组
         * @return
         */
        public Long sinterstore(String dstkey, String... keys) {
            return jedis.sinterstore(dstkey, keys);
        }
    
        /**
         * 通过key返回所有set的并集
         *
         * @param keys 可以 是一个string 也可以是一个string数组
         * @return
         */
        public Set<String> sunion(String... keys) {
            return jedis.sunion(keys);
        }
    
        /**
         * 通过key返回所有set的并集,并存入到新的set中
         *
         * @param dstkey
         * @param keys   可以 是一个string 也可以是一个string数组
         * @return
         */
        public Long sunionstore(String dstkey, String... keys) {
            return jedis.sunionstore(dstkey, keys);
        }
    
        /**
         * 通过key将set中的value移除并添加到第二个set中
         *
         * @param srckey 需要移除的
         * @param dstkey 添加的
         * @param member set中的value
         * @return
         */
        public Long smove(String srckey, String dstkey, String member) {
            return jedis.smove(srckey, dstkey, member);
        }
    
        /**
         * 通过key获取set中value的个数
         *
         * @param key
         * @return
         */
        public Long scard(String key) {
            return jedis.scard(key);
        }
    
        /**
         * 通过key判断value是否是set中的元素
         *
         * @param key
         * @param member
         * @return
         */
        public Boolean sismember(String key, String member) {
            return jedis.sismember(key, member);
        }
    
        /**
         * 通过key获取set中随机的value,不删除元素
         *
         * @param key
         * @return
         */
        public String srandmember(String key) {
            return jedis.srandmember(key);
        }
    
        /**
         * 通过key获取set中所有的value
         *
         * @param key
         * @return
         */
        public Set<String> smembers(String key) {
            return jedis.smembers(key);
        }
    
    
        /**
         * 通过key向zset中添加value,score,其中score就是用来排序的
         * 如果该value已经存在则根据score更新元素
         *
         * @param key
         * @param score
         * @param member
         * @return
         */
        public Long zadd(String key, double score, String member) {
            return jedis.zadd(key, score, member);
        }
    
        /**
         * 通过key删除在zset中指定的value
         *
         * @param key
         * @param members 可以 是一个string 也可以是一个string数组
         * @return
         */
        public Long zrem(String key, String... members) {
            return jedis.zrem(key, members);
        }
    
        /**
         * 通过key增加该zset中value的score的值
         *
         * @param key
         * @param score
         * @param member
         * @return
         */
        public Double zincrby(String key, double score, String member) {
            return jedis.zincrby(key, score, member);
        }
    
        /**
         * 通过key返回zset中value的排名
         * 下标从小到大排序
         *
         * @param key
         * @param member
         * @return
         */
        public Long zrank(String key, String member) {
            return jedis.zrank(key, member);
        }
    
        /**
         * 通过key返回zset中value的排名
         * 下标从大到小排序
         *
         * @param key
         * @param member
         * @return
         */
        public Long zrevrank(String key, String member) {
            return jedis.zrevrank(key, member);
        }
    
        /**
         * 通过key将获取score从start到end中zset的value
         * socre从大到小排序
         * 当start为0 end为-1时返回全部
         *
         * @param key
         * @param start
         * @param end
         * @return
         */
        public Set<String> zrevrange(String key, long start, long end) {
            return jedis.zrevrange(key, start, end);
        }
    
        /**
         * 通过key返回指定score内zset中的value
         *
         * @param key
         * @param max
         * @param min
         * @return
         */
        public Set<String> zrangebyscore(String key, String max, String min) {
            return jedis.zrevrangeByScore(key, max, min);
        }
    
        /**
         * 通过key返回指定score内zset中的value
         *
         * @param key
         * @param max
         * @param min
         * @return
         */
        public Set<String> zrangeByScore(String key, double max, double min) {
            return jedis.zrevrangeByScore(key, max, min);
        }
    
        /**
         * 返回指定区间内zset中value的数量
         *
         * @param key
         * @param min
         * @param max
         * @return
         */
        public Long zcount(String key, String min, String max) {
            return jedis.zcount(key, min, max);
        }
    
        /**
         * 通过key返回zset中的value个数
         *
         * @param key
         * @return
         */
        public Long zcard(String key) {
            return jedis.zcard(key);
        }
    
        /**
         * 通过key获取zset中value的score值
         *
         * @param key
         * @param member
         * @return
         */
        public Double zscore(String key, String member) {
            return jedis.zscore(key, member);
        }

    事务

        public static void testTransaction() {
            // MULTI  标记一个事务块的开始,将一系列的命令放入队列中,后面使用
            // EXEC执行,
            // DISCAED 取消事务,放弃执行事务块内的命令
            // WATCH  监视一个(或多个)key,如果在事务执行之前这个(或这些)key被其他命令锁改动,那么事务将被打断
            Transaction t = jedis.multi();
            String watch = jedis.watch("testabcd");
            Transaction multi=jedis.multi();//开启redis事务
            try {
                //设置数据
                multi.set("ka", "va");
                multi.set("kb", "vb");
                int num=1/0;
                multi.set("kc", "vc");
            } catch (Exception e) {
                //multi.discard();
                e.printStackTrace();
            }
            //redis事务提交
            multi.exec(); // redis成功保存ka,kb,不会保存kc。
        }
    
        public static void testTransaction2() {
            // MULTI  标记一个事务块的开始,将一系列的命令放入队列中,后面使用
            // EXEC执行,
            // DISCAED 取消事务,放弃执行事务块内的命令
            // WATCH  监视一个(或多个)key,如果在事务执行之前这个(或这些)key被其他命令锁改动,那么事务将被打断
            Transaction t = jedis.multi();
            String watch = jedis.watch("testabcd");
            Transaction multi=jedis.multi();//开启redis事务
            try {
                //设置数据
                multi.set("ka", "va");
                multi.set("kb", "vb");
                int num=1/0;
                multi.set("kc", "vc");
            } catch (Exception e) {
                multi.discard();
                e.printStackTrace();
            }
            //redis事务提交
            multi.exec(); // redis不会保存ka,kb,kc.
        }

    管道

    public class JedisPipeline {
    
        private static Jedis jedis = RedisConfig.getJedis();
    
        public static void main(String [] args){
            int count = 100000;
            long start = System.currentTimeMillis();
            withOutPipe(count);
            long end = System.currentTimeMillis();
            System.out.println("withoutPipeline: " + (end-start));// withoutPipeline: 4070
    
            start = System.currentTimeMillis();
            withPipe(count);
            end = System.currentTimeMillis();
            System.out.println("usePipeline: " + (end-start));//usePipeline: 131
        }
    
        public static void configSet(int count){
            jedis.configSet("timeout", "1");
            jedis.disconnect();
        }
    
        public static void withOutPipe(int count){
            for(int i =0; i<count; i++){
                jedis.incr("testKey1");
            }
            jedis.disconnect();
        }
    
        public static void withPipe(int count){
            Pipeline pl = jedis.pipelined();
            for(int i =0; i<count; i++){
                pl.incr("testKey1");
            }
            pl.sync();
            jedis.disconnect();
        }
    
    }

     注:Jedis类一般只能对一台redis-master进行数据操作,所以面对redis-cluster多台master与slave的群集,Jedis类就不能满足了。这个时候我们需要引用另外一个操作类:JedisCluster类。

    参考:https://blog.csdn.net/qq_35375529/article/details/90266843

    https://www.jianshu.com/p/ae949ffbd5af

  • 相关阅读:
    win7下如何配置ODBC数据源
    串口小票打印机调试命令
    如何测试一个网页登陆界面
    Cookie是否是httponly
    XSS攻击 (安全方面)和传统防御技术
    Linux下查看文件和文件夹大小
    linux停止和查看启动服务的命令使用方法
    查看Linux下系统资源占用常用命令(top、free、uptime)
    三种经典iPhone上网络抓包方法详解
    如何用Fiddler对Android应用进行抓包
  • 原文地址:https://www.cnblogs.com/yrjns/p/11722907.html
Copyright © 2011-2022 走看看