zoukankan      html  css  js  c++  java
  • Redis入门实战(4)-Jedis操作redis

    本文主要介绍使用jedis操作redis,使用到的软件版本:Java 1.8.0_191、Redis 5.0.8、Jedis 3.3.0。

    1、引入依赖

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

    2、基本操作

    package com.inspur.demo.general.redis;
    
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import redis.clients.jedis.Jedis;
    
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    
    /**
     * 使用jedis来实现对redis的基本操作
     */
    public class JedisBaseCase {
        private Jedis jedis;
    
        @Before
        public void before() {
            jedis = new Jedis("10.49.196.10");
            jedis.auth("123456");
        }
    
        @After
        public void after() {
            jedis.close();
        }
    
        /***********************************Key begin*****************************/
        /**
         * 清空所有key
         */
        @Test
        public void flushAll() {
            String status = jedis.flushAll();
            System.out.println(status);
        }
    
        /**
         * 重命名key
         */
        @Test
        public void rename() {
            String status = jedis.rename("name", "name2");
            System.out.println(status);
        }
    
        /**
         * 重命名key,仅当新key不存在时才执行
         * 返回值:
         * 1:oldKey被重新命名
         * 0:newKey已存在
         */
        @Test
        public void renamenx() {
            long status = jedis.renamenx("name", "name3");
            System.out.println(status);
        }
    
        /**
         * 设置key的过期时间,以秒为单位
         * 返回值:
         * 1:成功设置了过期时间
         * 0:key不存在
         */
        @Test
        public void expired() {
            long status = jedis.expire("name", 100);
            System.out.println(status);
        }
    
        /**
         * 设置key的过期时间,它是距历元(即格林威治标准时间1970年1月1日00:00:00)的秒数。
         * 返回值:
         * 1:成功设置了过期时间
         * 0:key不存在
         */
        @Test
        public void expiredAt() {
            long status = jedis.expireAt("name", System.currentTimeMillis()/1000 + 100);
            System.out.println(status);
        }
    
        /**
         * 查询key的过期时间,单位秒
         * 返回值:
         *  -1: 表示没有过期时间
         *  -2:表示key不存在
         *  其他:key的过期时间
         */
        @Test
        public void ttl() {
            long time = jedis.ttl("name");
            System.out.println(time);
        }
    
        /**
         * 持久化key
         * 返回值:
         *  1:成功持久化了
         *  0:key不存在
         */
        @Test
        public void persist() {
            long state = jedis.persist("name");
            System.out.println(state);
        }
    
    
        /**
         * 删除key
         * 返回值:
         * 成功删除的key的个数
         * 0表示key都不存在
         */
        @Test
        public void del() {
            long state = jedis.del("name", "name1");
            System.out.println(state);
        }
        /***********************************Key end*******************************/
        /***********************************String begin***************************/
        @Test
        public void set() {
            String status = jedis.set("name", "mayun");
            System.out.println(status);
        }
    
        /**
         * 添加有过期时间的记录
         */
        @Test
        public void setex() {
            String status = jedis.setex("name", 100, "mayun");
            System.out.println(status);
        }
    
        /**
         * 添加一条记录,仅当给定的key不存在时才插入
         * 返回值:
         * 1:成功设置了key
         * 0:可以不存在
         */
        @Test
        public void setnx() {
            long code = jedis.setnx("name", "mayun");
            System.out.println(code);
        }
    
        @Test
        public void mset() {
            String status = jedis.mset("name", "mayun", "age", "50");
            System.out.println(status);
        }
    
        @Test
        public void get() {
            String value = jedis.get("name");
            System.out.println(value);
        }
    
        @Test
        public void mget() {
            List<String> value = jedis.mget("name", "age");
            System.out.println(value);
        }
    
        /**
         * 将key对应的value减去指定的值,只有value可以转为数字时该方法才可用
         * 返回相减后的值
         */
        @Test
        public void decrBy() {
            long value = jedis.decrBy("salary", 10);
            System.out.println(value);
        }
    
        /**
         * 将key对应的value加上指定的值,只有value可以转为数字时该方法才可用
         * 返回相加后的值
         *
         * <b>可以作为获取唯一id的方法</b>
         */
        @Test
        public void incrBy() {
            long value = jedis.incrBy("salary", 10);
            System.out.println(value);
        }
    
        /**
         * 设置Key的值并返回老的值
         */
        @Test
        public void getSet() {
            String value = jedis.getSet("name", "马化腾");
            System.out.println(value);
        }
    
        /***********************************String end***************************/
    
        /***********************************list begin***************************/
        /**
         * 将一个或多个值插入到列表头部
         * 返回插入队列的数据的个数
         */
        @Test
        public void lpush() {
            Long num = jedis.lpush("list", "a", "b", "c");
            System.out.println(num);
        }
    
        /**
         * 将一个或多个值插入到列表尾部
         * 返回插入队列的数据的个数
         */
        @Test
        public void rpush() {
            Long num = jedis.rpush("list", "a", "b", "c");
            System.out.println(num);
        }
    
        /**
         * 将一个或多个值插入到已存在的列表头部
         * 返回插入队列的数据的个数
         */
        @Test
        public void lpushx() {
            Long num = jedis.lpushx("list", "1", "2", "3");
            System.out.println(num);
        }
    
        /**
         * 将一个或多个值插入到已存在的列表尾部
         * 返回插入队列的数据的个数
         */
        @Test
        public void rpushx() {
            Long num = jedis.rpushx("list", "1", "2", "3");
            System.out.println(num);
        }
    
        /**
         * 返回列表指定范围内的数据
         */
        @Test
        public void lrange() {
            List<String> list = jedis.lrange("list", 0, 5);
            System.out.println(list);
        }
        /***********************************list end***************************/
    
        /***********************************hash begin***************************/
        /**
         * 返回值新增加的field的个数,如果field都已存在则更新并返回0
         */
        @Test
        public void hset() {
            HashMap<String, String> values = new HashMap<>();
            values.put("age", "50");
            values.put("sex", "male");
            long code = jedis.hset("mayun", values);
            System.out.println(code);
            code = jedis.hset("mayun", "address", "杭州");
            System.out.println(code);
        }
    
        @Test
        public void hgetAll() {
            Map<String, String> value = jedis.hgetAll("mayun");
            System.out.println(value);
        }
    
        /**
         * 将field对应的value加上指定的值,只有value可以转为数字时该方法才可用
         * 返回增加后的值
         */
        @Test
        public void hincrBy() {
            long value = jedis.hincrBy("mayun", "age", 1);
            System.out.println(value);
        }
    
        /***********************************hash begin***************************/
    
        /***********************************set begin***************************/
        /**
         * 往set里增加元素
         * 成功增加元素的个数,如果都已存在返回0
         */
        @Test
        public void sadd() {
            long value = jedis.sadd("set", "a", "b");
            System.out.println(value);
        }
    
        /**
         * 移除set中的元素
         * 1:成功移除
         * 0:元素不存在
         */
        @Test
        public void srem() {
            long value = jedis.srem("set", "a");
            System.out.println(value);
        }
    
        /**
         * 获取set里的所有元素
         */
        @Test
        public void smembers() {
            Set<String> value = jedis.smembers("set");
            System.out.println(value);
        }
    
        /***********************************set begin***************************/
    
        /***********************************sorted set begin***************************/
        /**
         * 往sorted set里增加元素
         * 1: 成功增加
         * 0: 元素已存在
         */
        @Test
        public void zadd() {
            long value = jedis.zadd("sortedset", 1, "a");
            System.out.println(value);
            value = jedis.zadd("sortedset", 2, "b");
            System.out.println(value);
        }
    
        /**
         * 移除sorted set中的元素
         * 1:成功移除
         * 0:元素不存在
         */
        @Test
        public void zrem() {
            long value = jedis.zrem("sortedset", "a");
            System.out.println(value);
        }
    
        /**
         * 获取set里的所有元素
         */
        @Test
        public void zrange() {
            Set<String> value = jedis.zrange("sortedkey", 0, 5);
            System.out.println(value);
        }
        /***********************************sorted set end***************************/
    
        /***********************************hyper begin***************************/
        /**
         * 添加指定元素到HyperLogLog中
         * 返回成功天的个数,如果元素都已存在则返回0
         */
        @Test
        public void pfadd() {
            long code = jedis.pfadd("hyper", "a", "b", "d");
            System.out.println(code);
        }
    
        /**
         * 返回给定HyperLogLog的基数估算值
         */
        @Test
        public void pfcount() {
            long value = jedis.pfcount("hyper");
            System.out.println(value);
        }
        /***********************************hyper end***************************/
    }

    3、高级操作

    package com.inspur.demo.general.redis;
    
    import org.junit.Before;
    import org.junit.Test;
    import redis.clients.jedis.*;
    
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Set;
    
    /**
     * 高级操作
     */
    public class JedisAdvancedCase {
        private JedisPoolConfig config;
    
        @Before
        public void before() {
            config = new JedisPoolConfig();
            config.setMaxWaitMillis(1000 * 30);//当连接池内的连接耗尽时,最大的等待时间
            config.setMaxTotal(20);//资源池的最大连接数
            config.setMaxIdle(10);//资源池的最大空闲连接数
            config.setMinIdle(5);//资源池的最小空闲连接数
            config.setTestOnBorrow(true);//获取连接实例时,是否进行测试,默认false
            config.setTestWhileIdle(true);//是否开启空闲资源检测, 默认false
            config.setTimeBetweenEvictionRunsMillis(1000 * 10);//空闲资源的检测周期
        }
    
        /**
         * 管道操作,可以挺高性能
         */
        @Test
        public void pipelined() {
            Jedis jedis = new Jedis("10.49.196.10");
            jedis.auth("123456");
            Pipeline pipeline = jedis.pipelined();
            for (int i = 0; i < 100; i++) {
                pipeline.set("key" + i, i + "");
            }
            pipeline.sync();
            pipeline.close();
            jedis.close();
        }
    
        /**
         * 连接池操作
         */
        @Test
        public void jedisPool() {
            JedisPool pool = new JedisPool(config, "10.49.196.10", 6379, 1000 * 10, "123456");
            //获取Jedis实列
            Jedis jedis = pool.getResource();
            System.out.println(jedis.get("name"));
            jedis.close();
            pool.close();
        }
    
        /**
         * 哨兵模式
         */
        @Test
        public void jedisSentinelPool() {
            Set<String> sentinels = new HashSet<>();
            sentinels.add("10.49.196.20:26379");
            sentinels.add("10.49.196.21:26379");
            sentinels.add("10.49.196.22:26379");
            JedisSentinelPool pool = new JedisSentinelPool("mymaster", sentinels, config, 1000 * 5, "123456");
            //获取Jedis实列
            Jedis jedis = pool.getResource();
            System.out.println(jedis.get("name"));
            jedis.close();
            pool.close();
        }
    
        /**
         * 集群模式
         */
        @Test
        public void jedisCluster() {
            Set<HostAndPort> set = new HashSet<HostAndPort>();
            set.add(new HostAndPort("10.49.196.20", 7000));
            set.add(new HostAndPort("10.49.196.20", 7001));
            set.add(new HostAndPort("10.49.196.21", 7000));
            set.add(new HostAndPort("10.49.196.21", 7001));
            set.add(new HostAndPort("10.49.196.22", 7000));
            set.add(new HostAndPort("10.49.196.22", 7001));
            JedisCluster cluster = new JedisCluster(set, 1000 * 5, 1000 * 5, 5, "123456", config);
            //JedisCluster的基础操作和Jedis很类似
    
            //key
            System.out.println("判断key是否存在:" + cluster.exists("name"));
            System.out.println("查询key的过期时间:" + cluster.ttl("name"));
    
            //String
            System.out.println("设置键值对:" + cluster.set("name", "mahuateng"));
            System.out.println("获取key对应的值:" + cluster.get("name"));
    
            //List
            System.out.println("将一个或多个值插入到列表头部:" + cluster.lpush("list", "a", "b", "c"));
            System.out.println("返回列表指定范围内的数据:" + cluster.lrange("list", 0, 5));
    
            //Hash
            HashMap<String, String> values = new HashMap<>();
            values.put("age", "50");
            values.put("sex", "male");
            System.out.println("在hash中设置field及value:" + cluster.hset("mayun", values));
            System.out.println("在hash中所有属性及值:" + cluster.hgetAll("mayun"));
    
            //set
            System.out.println("往set里增加元素:" + cluster.sadd("set", "a", "b"));
            System.out.println("取set里的所有元素:" + cluster.smembers("set"));
    
            //sorted set
            System.out.println("往sorted set里增加元素1:" + cluster.zadd("sortedset", 1, "a"));
            System.out.println("往sorted set里增加元素2:" + cluster.zadd("sortedset", 2, "b"));
            System.out.println("获取sorted set里的所有元素:" + cluster.zrange("sortedset",0, 5));
    
            //集群信息
            System.out.println("集群节点信息:" + cluster.getClusterNodes());
            cluster.close();
        }
    }

    4、JedisPoolConfig参数说明

    JedisPoolConfig用来设置连接池的相关属性,具体参数如下:

    参数名称 说明 默认值 建议
    maxTotal 资源池中的最大连接数 8  
    maxIdle 资源池中的最大空闲连接数 8  
    minIdle 资源池中的最少空闲连接数 0  
    blockWhenExhausted 当资源池用尽后,调用者是否要等待。只有当值为true时,下面的maxWaitMillis才会生效。 true 建议使用默认值
    maxWaitMillis 当资源池连接用尽后,调用者的最大等待时间(单位为毫秒)。 -1(表示永不超时) 不建议使用默认值
    testOnBorrow 向资源池借用连接时是否做连接有效性检测(ping)。检测到的无效连接将会被移除。 false 业务量很大时候建议设置为false,减少一次ping的开销。
    testOnReturn 向资源池归还连接时是否做连接有效性检测(ping)。检测到无效连接将会被移除。 false 业务量很大时候建议设置为false,减少一次ping的开销。
    jmxEnabled 是否开启JMX监控 true 建议开启,注意应用本身也需要开启。
    testWhileIdle 是否开启空闲资源检测 false 建议开启
    timeBetweenEvictionRunsMillis 空闲资源的检测周期(单位为毫秒) -1(不检测) 建议设置
    minEvictableIdleTimeMillis 资源池中资源的最小空闲时间(单位为毫秒),达到此值后空闲资源将被移除。 1800000(即30分钟) 可根据自身业务决定,一般默认值即可
    numTestsPerEvictionRun 做空闲资源检测时,每次检测资源的个数。 3 可根据自身应用连接数进行微调,如果设置为 -1,就是对所有连接做空闲监测。
  • 相关阅读:
    SQLSERVER排查CPU占用高的情况
    bootstrap布局两列或者多列表单
    ASP.NET Redis 开发
    .NET 环境中使用RabbitMQ
    EasyNetQ介绍
    .Net使用RabbitMQ详解
    ASp.net中Froms验证方式
    全国-城市-百度地图中心点坐标
    IIS7.0下 HTTP 错误 404.15
    asp.net报错“尝试读取或写入受保护的内存。这通常指示其他内存已损坏”的解决办法
  • 原文地址:https://www.cnblogs.com/wuyongyin/p/13156670.html
Copyright © 2011-2022 走看看