• Redis基本命令的学习和Jedis


    使用Java来操作Redis,Jedis是Redis官方推荐使用的Java连接redis的客户端的开发工具,使用java操作redis中间件。

    测试

    1.导入对应的依赖

      <dependencies>
            
            <dependency>
                <groupId>redis.clientsgroupId>
                <artifactId>jedisartifactId>
                <version>3.2.0version>
            dependency>
            
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>fastjsonartifactId>
                <version>1.2.48version>
            dependency>
    
        dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    2.编码测试:

    连接数据库
    操作命令
    断开连接
    import redis.clients.jedis.Jedis;
    public class TestPing {
    public static void main(String[] args) {
    //1. new jedis 对象即可
    Jedis jedis = new Jedis(“192.168.56.130”,6379); //自己虚拟机的ip地址
    jedis.auth(“123456”);

        // jedis 所有的命令就是我们之前学习的所有指令
        System.out.println(jedis.ping());
    
    }
    
    • 1
    • 2
    • 3
    • 4

    }
    常用的API
    String 、list、set 、hash、Zset等 所有的api命令,就是我们对应的上面学习的指令,一个都没有变化!

    判断keys * 以及一些基本方法

    import redis.clients.jedis.Jedis;
    
    import java.util.Set;
    
    public class TestKey {
        public static void main(String[] args) {
            Jedis jedis = new Jedis("192.168.56.130",6379);
            jedis.auth("123456");
    
            System.out.println("清空数据:"+jedis.flushDB());
            System.out.println("判断某个键是否存在:"+jedis.exists("username"));
            System.out.println("新增<'username','kuangshen'>的键值对:"+jedis.set("username", "kuangshen"));
            System.out.println("新增<'password','password'>的键值对:"+jedis.set("password", "password"));
            System.out.print("系统中所有的键如下:");
            Set<String> keys = jedis.keys("*");
            System.out.println(keys);
            System.out.println("删除键password:"+jedis.del("password"));
            System.out.println("判断键password是否存在:"+jedis.exists("password"));
            System.out.println("查看键username所存储的值的类型:"+jedis.type("username"));
            System.out.println("随机返回key空间的一个:"+jedis.randomKey());
            System.out.println("重命名key:"+jedis.rename("username","name"));
            System.out.println("取出改后的name:"+jedis.get("name"));
            System.out.println("按索引查询:"+jedis.select(0));
            System.out.println("删除当前选择数据库中的所有key:"+jedis.flushDB());
            System.out.println("返回当前数据库中key的数目:"+jedis.dbSize());
            System.out.println("删除所有数据库中的所有key:"+jedis.flushAll());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    对String操作的命令

    import redis.clients.jedis.Jedis;
    import java.util.concurrent.TimeUnit;
    
    public class TestString {
        public static void main(String[] args) {
           Jedis jedis = new Jedis("192.168.56.130",6379);
            jedis.auth("123456");
    
            jedis.flushDB();
            System.out.println("===========增加数据===========");
            System.out.println(jedis.set("key1","value1"));
            System.out.println(jedis.set("key2","value2"));
            System.out.println(jedis.set("key3", "value3"));
            System.out.println("删除键key2:"+jedis.del("key2"));
            System.out.println("获取键key2:"+jedis.get("key2"));
            System.out.println("修改key1:"+jedis.set("key1", "value1Changed"));
            System.out.println("获取key1的值:"+jedis.get("key1"));
            System.out.println("在key3后面加入值:"+jedis.append("key3", "End"));
            System.out.println("key3的值:"+jedis.get("key3"));
            System.out.println("增加多个键值对:"+jedis.mset("key01","value01","key02","value02","key03","value03"));
            System.out.println("获取多个键值对:"+jedis.mget("key01","key02","key03"));
            System.out.println("获取多个键值对:"+jedis.mget("key01","key02","key03","key04"));
            System.out.println("删除多个键值对:"+jedis.del("key01","key02"));
            System.out.println("获取多个键值对:"+jedis.mget("key01","key02","key03"));
    
            jedis.flushDB();
            System.out.println("===========新增键值对防止覆盖原先值==============");
            System.out.println(jedis.setnx("key1", "value1"));
            System.out.println(jedis.setnx("key2", "value2"));
            System.out.println(jedis.setnx("key2", "value2-new"));
            System.out.println(jedis.get("key1"));
            System.out.println(jedis.get("key2"));
    
            System.out.println("===========新增键值对并设置有效时间=============");
            System.out.println(jedis.setex("key3", 2, "value3"));
            System.out.println(jedis.get("key3"));
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(jedis.get("key3"));
    
            System.out.println("===========获取原值,更新为新值==========");
            System.out.println(jedis.getSet("key2", "key2GetSet"));
            System.out.println(jedis.get("key2"));
    
            System.out.println("获得key2的值的字串:"+jedis.getrange("key2", 2, 4));
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    对List的命令

    import redis.clients.jedis.Jedis;
    public class TestList {
        public static void main(String[] args) {
            Jedis jedis = new Jedis("192.168.56.130",6379);
            jedis.auth("123456");
            jedis.flushDB();
            System.out.println("===========添加一个list===========");
            jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap");
            jedis.lpush("collections", "HashSet");
            jedis.lpush("collections", "TreeSet");
            jedis.lpush("collections", "TreeMap");
            System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));//-1代表倒数第一个元素,-2代表倒数第二个元素,end为-1表示查询全部
            System.out.println("collections区间0-3的元素:"+jedis.lrange("collections",0,3));
            System.out.println("===============================");
            // 删除列表指定的值 ,第二个参数为删除的个数(有重复时),后add进去的值先被删,类似于出栈
            System.out.println("删除指定元素个数:"+jedis.lrem("collections", 2, "HashMap"));
            System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
            System.out.println("删除下表0-3区间之外的元素:"+jedis.ltrim("collections", 0, 3));
            System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
            System.out.println("collections列表出栈(左端):"+jedis.lpop("collections"));
            System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
            System.out.println("collections添加元素,从列表右端,与lpush相对应:"+jedis.rpush("collections", "EnumMap"));
            System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
            System.out.println("collections列表出栈(右端):"+jedis.rpop("collections"));
            System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
            System.out.println("修改collections指定下标1的内容:"+jedis.lset("collections", 1, "LinkedArrayList"));
            System.out.println("collections的内容:"+jedis.lrange("collections", 0, -1));
            System.out.println("===============================");
            System.out.println("collections的长度:"+jedis.llen("collections"));
            System.out.println("获取collections下标为2的元素:"+jedis.lindex("collections", 2));
            System.out.println("===============================");
            jedis.lpush("sortedList", "3","6","2","0","7","4");
            System.out.println("sortedList排序前:"+jedis.lrange("sortedList", 0, -1));
            System.out.println(jedis.sort("sortedList"));
            System.out.println("sortedList排序后:"+jedis.lrange("sortedList", 0, -1));
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    对set操作命令

    import redis.clients.jedis.Jedis;
    
    public class TestSet {
        public static void main(String[] args) {
            Jedis jedis = new Jedis("192.168.56.130",6379);
            jedis.auth("123456");
            jedis.flushDB();
            System.out.println("============向集合中添加元素(不重复)============");
            System.out.println(jedis.sadd("eleSet", "e1","e2","e4","e3","e0","e8","e7","e5"));
            System.out.println(jedis.sadd("eleSet", "e6"));
            System.out.println(jedis.sadd("eleSet", "e6"));
            System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet"));
            System.out.println("删除一个元素e0:"+jedis.srem("eleSet", "e0"));
            System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet"));
            System.out.println("删除两个元素e7和e6:"+jedis.srem("eleSet", "e7","e6"));
            System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet"));
            System.out.println("随机的移除集合中的一个元素:"+jedis.spop("eleSet"));
            System.out.println("随机的移除集合中的一个元素:"+jedis.spop("eleSet"));
            System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet"));
            System.out.println("eleSet中包含元素的个数:"+jedis.scard("eleSet"));
            System.out.println("e3是否在eleSet中:"+jedis.sismember("eleSet", "e3"));
            System.out.println("e1是否在eleSet中:"+jedis.sismember("eleSet", "e1"));
            System.out.println("e1是否在eleSet中:"+jedis.sismember("eleSet", "e5"));
            System.out.println("=================================");
            System.out.println(jedis.sadd("eleSet1", "e1","e2","e4","e3","e0","e8","e7","e5"));
            System.out.println(jedis.sadd("eleSet2", "e1","e2","e4","e3","e0","e8"));
            System.out.println("将eleSet1中删除e1并存入eleSet3中:"+jedis.smove("eleSet1", "eleSet3", "e1"));//移到集合元素
            System.out.println("将eleSet1中删除e2并存入eleSet3中:"+jedis.smove("eleSet1", "eleSet3", "e2"));
            System.out.println("eleSet1中的元素:"+jedis.smembers("eleSet1"));
            System.out.println("eleSet3中的元素:"+jedis.smembers("eleSet3"));
            System.out.println("============集合运算=================");
            System.out.println("eleSet1中的元素:"+jedis.smembers("eleSet1"));
            System.out.println("eleSet2中的元素:"+jedis.smembers("eleSet2"));
            System.out.println("eleSet1和eleSet2的交集:"+jedis.sinter("eleSet1","eleSet2"));
            System.out.println("eleSet1和eleSet2的并集:"+jedis.sunion("eleSet1","eleSet2"));
            System.out.println("eleSet1和eleSet2的差集:"+jedis.sdiff("eleSet1","eleSet2"));//eleSet1中有,eleSet2中没有
            jedis.sinterstore("eleSet4","eleSet1","eleSet2");//求交集并将交集保存到dstkey的集合
            System.out.println("eleSet4中的元素:"+jedis.smembers("eleSet4"));
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    对hash操作的命令

    import redis.clients.jedis.Jedis;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class TestHash {
        public static void main(String[] args) {
            Jedis jedis = new Jedis("192.168.56.130",6379);
            jedis.auth("123456");
            jedis.flushDB();
            Map<String,String> map = new HashMap<String,String>();
            map.put("key1","value1");
            map.put("key2","value2");
            map.put("key3","value3");
            map.put("key4","value4");
            //添加名称为hash(key)的hash元素
            jedis.hmset("hash",map);
            //向名称为hash的hash中添加key为key5,value为value5元素
            jedis.hset("hash", "key5", "value5");
            System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash"));//return Map
            System.out.println("散列hash的所有键为:"+jedis.hkeys("hash"));//return Set
            System.out.println("散列hash的所有值为:"+jedis.hvals("hash"));//return List
            System.out.println("将key6保存的值加上一个整数,如果key6不存在则添加key6:"+jedis.hincrBy("hash", "key6", 6));
            System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash"));
            System.out.println("将key6保存的值加上一个整数,如果key6不存在则添加key6:"+jedis.hincrBy("hash", "key6", 3));
            System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash"));
            System.out.println("删除一个或者多个键值对:"+jedis.hdel("hash", "key2"));
            System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash"));
            System.out.println("散列hash中键值对的个数:"+jedis.hlen("hash"));
            System.out.println("判断hash中是否存在key2:"+jedis.hexists("hash","key2"));
            System.out.println("判断hash中是否存在key3:"+jedis.hexists("hash","key3"));
            System.out.println("获取hash中的值:"+jedis.hmget("hash","key3"));
            System.out.println("获取hash中的值:"+jedis.hmget("hash","key3","key4"));
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    对Zset操作的命令

    事务

    import com.alibaba.fastjson.JSONObject;
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.Transaction;
    
    public class TestTX {
        public static void main(String[] args) {
            Jedis jedis = new Jedis("192.168.56.130",6379);
            jedis.auth("123456");
        jedis.flushDB();
    
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("hello","world");
            jsonObject.put("name","jihu");
            //开启事务
            Transaction multi = jedis.multi();
            String result = jsonObject.toJSONString();
            //jedis.watch(result) //给result加乐观锁
    
            try {
                multi.set("user1",result);
                multi.set("user2",result);
                int i = 1/0; //代码抛出异常,事务执行失败
    
                multi.exec();  //执行事务
                     } catch (Exception exception) {
                multi.discard();  //放弃事务
                exception.printStackTrace();
            }finally {
                System.out.println(jedis.get("user1"));
                System.out.println(jedis.get("user2"));
                jedis.close(); //关闭连接
            }
        }
    }
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    SpringBoot整合

    SpringBoot 操作数据:spring-data jpa jdbc mongodb redis!

    SpringData 也是和 SpringBoot 齐名的项目!

    说明: 在 SpringBoot2.x 之后,原来使用的jedis 被替换为了 lettuce?

    jedis : 采用的直连,多个线程操作的话,是不安全的,如果想要避免不安全的,使用 jedis pool 连接池! 更像 BIO 模式

    lettuce : 采用netty,实例可以再多个线程中进行共享,不存在线程不安全的情况!可以减少线程数据了,更像 NIO 模式

    源码分析

    @Bean // 我们可以自己定义一个redisTemplate来替换这个默认的!
    @ConditionalOnMissingBean(name = "redisTemplate") 
    
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
    // 默认的 RedisTemplate 没有过多的设置,redis 对象都是需要序列化!
    // 两个泛型都是 Object, Object 的类型,我们后使用需要强制转换 
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
    
    @Bean
    @ConditionalOnMissingBean // 由于 String 是redis中最常使用的类型,所以说单独提出来了一个bean!
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    propertiers文件配置

    #springboot所有的配置类都有一个自动配置类 :RedisAutoConfiguration
    # (RedisAutoConfiguration它在RedisAutoConfiguration/META-INF/spring.factories文件中)
    #自动配置类都会绑定一个 properties配置文件 RedisProperties
    
    #配置Redis
    spring.redis.host=192.168.56.130
    spring.redis.port=6379
    spring.redis.password=123456
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    测试

    @SpringBootTest
    class Redis02SpringbootApplicationTests {
    
    	@Autowired
    	private RedisTemplate redisTemplate;
    
    	@Test
    	void contextLoads() {
    
    		//redisTemplate  操作不同的数据类型,api和我们的指令是一样的
    		//redisTemplate.opsForValue()  表示操作字符串 类似String
    		//redisTemplate.opsForList()  表示操作List ,类似list
    		//等等
    		redisTemplate.opsForList();
    
    		//除了基本的操作,我们常用的方法都可以直接通过redisTemplate操作,比如事务和基本的CRUD
    
    		//获取redis的连接对象
    		//RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
    		//connection.flushDb();
    		//connection.flushAll();
    
    		redisTemplate.opsForValue().set("mykey","jihu");
    		System.out.println(redisTemplate.opsForValue().get("mykey"));
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    自定义RedisTemplate序列化配置

    我们来编写一个自己的 RedisTemplete

    @Configuration
    public class RedisConfig {
        // 这是我给大家写好的一个固定模板,大家在企业中,拿去就可以直接使用!
        // 自己定义了一个 RedisTemplate
        @Bean
        @SuppressWarnings("all")
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
            // 我们为了自己开发方便,一般直接使用 
            RedisTemplate<String, Object> template = new RedisTemplate<String,
            Object>();
            template.setConnectionFactory(factory);
    
        // Json序列化配置
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new
        Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // String 的序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
    
        return template;
    }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    RedisUtil配置(CRUD操作string,map,list,set)

    //在我们真实的开发中,或者你们的公司,一般都可以看到一个公司自己封装的RedisUtil
    @Component
    public final class RedisUtil {
    
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
    
        // =============================common============================
        /**
         * 指定缓存失效时间
         * @param key  键
         * @param time 时间(秒)
         */
        public boolean expire(String key, long time) {
            try {
                if (time > 0) {
                    redisTemplate.expire(key, time, TimeUnit.SECONDS);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 根据key 获取过期时间
         * @param key 键 不能为null
         * @return 时间(秒) 返回0代表为永久有效
         */
        public long getExpire(String key) {
            return redisTemplate.getExpire(key, TimeUnit.SECONDS);
        }
    
    
        /**
         * 判断key是否存在
         * @param key 键
         * @return true 存在 false不存在
         */
        public boolean hasKey(String key) {
            try {
                return redisTemplate.hasKey(key);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
    
        /**
         * 删除缓存
         * @param key 可以传一个值 或多个
         */
        @SuppressWarnings("unchecked")
        public void del(String... key) {
            if (key != null && key.length > 0) {
                if (key.length == 1) {
                    redisTemplate.delete(key[0]);
                } else {
                    redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
                }
            }
        }
    
    
        // ============================String=============================
    
        /**
         * 普通缓存获取
         * @param key 键
         * @return 值
         */
        public Object get(String key) {
            return key == null ? null : redisTemplate.opsForValue().get(key);
        }
    
        /**
         * 普通缓存放入
         * @param key   键
         * @param value 值
         * @return true成功 false失败
         */
    
        public boolean set(String key, Object value) {
            try {
                redisTemplate.opsForValue().set(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
    
        /**
         * 普通缓存放入并设置时间
         * @param key   键
         * @param value 值
         * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
         * @return true成功 false 失败
         */
    
        public boolean set(String key, Object value, long time) {
            try {
                if (time > 0) {
                    redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
                } else {
                    set(key, value);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
    
        /**
         * 递增
         * @param key   键
         * @param delta 要增加几(大于0)
         */
        public long incr(String key, long delta) {
            if (delta < 0) {
                throw new RuntimeException("递增因子必须大于0");
            }
            return redisTemplate.opsForValue().increment(key, delta);
        }
    
    
        /**
         * 递减
         * @param key   键
         * @param delta 要减少几(小于0)
         */
        public long decr(String key, long delta) {
            if (delta < 0) {
                throw new RuntimeException("递减因子必须大于0");
            }
            return redisTemplate.opsForValue().increment(key, -delta);
        }
    
    
        // ================================Map=================================
    
        /**
         * HashGet
         * @param key  键 不能为null
         * @param item 项 不能为null
         */
        public Object hget(String key, String item) {
            return redisTemplate.opsForHash().get(key, item);
        }
    
        /**
         * 获取hashKey对应的所有键值
         * @param key 键
         * @return 对应的多个键值
         */
        public Map<Object, Object> hmget(String key) {
            return redisTemplate.opsForHash().entries(key);
        }
    
        /**
         * HashSet
         * @param key 键
         * @param map 对应多个键值
         */
        public boolean hmset(String key, Map<String, Object> map) {
            try {
                redisTemplate.opsForHash().putAll(key, map);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
    
        /**
         * HashSet 并设置时间
         * @param key  键
         * @param map  对应多个键值
         * @param time 时间(秒)
         * @return true成功 false失败
         */
        public boolean hmset(String key, Map<String, Object> map, long time) {
            try {
                redisTemplate.opsForHash().putAll(key, map);
                if (time > 0) {
                    expire(key, time);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
    
        /**
         * 向一张hash表中放入数据,如果不存在将创建
         *
         * @param key   键
         * @param item  项
         * @param value 值
         * @return true 成功 false失败
         */
        public boolean hset(String key, String item, Object value) {
            try {
                redisTemplate.opsForHash().put(key, item, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
        /**
         * 向一张hash表中放入数据,如果不存在将创建
         *
         * @param key   键
         * @param item  项
         * @param value 值
         * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
         * @return true 成功 false失败
         */
        public boolean hset(String key, String item, Object value, long time) {
            try {
                redisTemplate.opsForHash().put(key, item, value);
                if (time > 0) {
                    expire(key, time);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
    
        /**
         * 删除hash表中的值
         *
         * @param key  键 不能为null
         * @param item 项 可以使多个 不能为null
         */
        public void hdel(String key, Object... item) {
            redisTemplate.opsForHash().delete(key, item);
        }
    
    
        /**
         * 判断hash表中是否有该项的值
         *
         * @param key  键 不能为null
         * @param item 项 不能为null
         * @return true 存在 false不存在
         */
        public boolean hHasKey(String key, String item) {
            return redisTemplate.opsForHash().hasKey(key, item);
        }
    
    
        /**
         * hash递增 如果不存在,就会创建一个 并把新增后的值返回
         *
         * @param key  键
         * @param item 项
         * @param by   要增加几(大于0)
         */
        public double hincr(String key, String item, double by) {
            return redisTemplate.opsForHash().increment(key, item, by);
        }
    
    
        /**
         * hash递减
         *
         * @param key  键
         * @param item 项
         * @param by   要减少记(小于0)
         */
        public double hdecr(String key, String item, double by) {
            return redisTemplate.opsForHash().increment(key, item, -by);
        }
    
    
        // ============================set=============================
    
        /**
         * 根据key获取Set中的所有值
         * @param key 键
         */
        public Set<Object> sGet(String key) {
            try {
                return redisTemplate.opsForSet().members(key);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
    
        /**
         * 根据value从一个set中查询,是否存在
         *
         * @param key   键
         * @param value 值
         * @return true 存在 false不存在
         */
        public boolean sHasKey(String key, Object value) {
            try {
                return redisTemplate.opsForSet().isMember(key, value);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
    
        /**
         * 将数据放入set缓存
         *
         * @param key    键
         * @param values 值 可以是多个
         * @return 成功个数
         */
        public long sSet(String key, Object... values) {
            try {
                return redisTemplate.opsForSet().add(key, values);
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
    
    
        /**
         * 将set数据放入缓存
         *
         * @param key    键
         * @param time   时间(秒)
         * @param values 值 可以是多个
         * @return 成功个数
         */
        public long sSetAndTime(String key, long time, Object... values) {
            try {
                Long count = redisTemplate.opsForSet().add(key, values);
                if (time > 0)
                    expire(key, time);
                return count;
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
    
    
        /**
         * 获取set缓存的长度
         *
         * @param key 键
         */
        public long sGetSetSize(String key) {
            try {
                return redisTemplate.opsForSet().size(key);
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
    
    
        /**
         * 移除值为value的
         *
         * @param key    键
         * @param values 值 可以是多个
         * @return 移除的个数
         */
    
        public long setRemove(String key, Object... values) {
            try {
                Long count = redisTemplate.opsForSet().remove(key, values);
                return count;
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
    
        // ===============================list=================================
    
        /**
         * 获取list缓存的内容
         *
         * @param key   键
         * @param start 开始
         * @param end   结束 0 到 -1代表所有值
         */
        public List<Object> lGet(String key, long start, long end) {
            try {
                return redisTemplate.opsForList().range(key, start, end);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
    
        /**
         * 获取list缓存的长度
         *
         * @param key 键
         */
        public long lGetListSize(String key) {
            try {
                return redisTemplate.opsForList().size(key);
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
    
    
        /**
         * 通过索引 获取list中的值
         *
         * @param key   键
         * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
         */
        public Object lGetIndex(String key, long index) {
            try {
                return redisTemplate.opsForList().index(key, index);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
    
        /**
         * 将list放入缓存
         *
         * @param key   键
         * @param value 值
         */
        public boolean lSet(String key, Object value) {
            try {
                redisTemplate.opsForList().rightPush(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
    
        /**
         * 将list放入缓存
         * @param key   键
         * @param value 值
         * @param time  时间(秒)
         */
        public boolean lSet(String key, Object value, long time) {
            try {
                redisTemplate.opsForList().rightPush(key, value);
                if (time > 0)
                    expire(key, time);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
    
        }
    
    
        /**
         * 将list放入缓存
         *
         * @param key   键
         * @param value 值
         * @return
         */
        public boolean lSet(String key, List<Object> value) {
            try {
                redisTemplate.opsForList().rightPushAll(key, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
    
        }
    
    
        /**
         * 将list放入缓存
         *
         * @param key   键
         * @param value 值
         * @param time  时间(秒)
         * @return
         */
        public boolean lSet(String key, List<Object> value, long time) {
            try {
                redisTemplate.opsForList().rightPushAll(key, value);
                if (time > 0)
                    expire(key, time);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
    
        /**
         * 根据索引修改list中的某条数据
         *
         * @param key   键
         * @param index 索引
         * @param value 值
         * @return
         */
    
        public boolean lUpdateIndex(String key, long index, Object value) {
            try {
                redisTemplate.opsForList().set(key, index, value);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    
    
        /**
         * 移除N个值为value
         *
         * @param key   键
         * @param count 移除多少个
         * @param value 值
         * @return 移除的个数
         */
    
        public long lRemove(String key, long count, Object value) {
            try {
                Long remove = redisTemplate.opsForList().remove(key, count, value);
                return remove;
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
    
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
    • 382
    • 383
    • 384
    • 385
    • 386
    • 387
    • 388
    • 389
    • 390
    • 391
    • 392
    • 393
    • 394
    • 395
    • 396
    • 397
    • 398
    • 399
    • 400
    • 401
    • 402
    • 403
    • 404
    • 405
    • 406
    • 407
    • 408
    • 409
    • 410
    • 411
    • 412
    • 413
    • 414
    • 415
    • 416
    • 417
    • 418
    • 419
    • 420
    • 421
    • 422
    • 423
    • 424
    • 425
    • 426
    • 427
    • 428
    • 429
    • 430
    • 431
    • 432
    • 433
    • 434
    • 435
    • 436
    • 437
    • 438
    • 439
    • 440
    • 441
    • 442
    • 443
    • 444
    • 445
    • 446
    • 447
    • 448
    • 449
    • 450
    • 451
    • 452
    • 453
    • 454
    • 455
    • 456
    • 457
    • 458
    • 459
    • 460
    • 461
    • 462
    • 463
    • 464
    • 465
    • 466
    • 467
    • 468
    • 469
    • 470
    • 471
    • 472
    • 473
    • 474
    • 475
    • 476
    • 477
    • 478
    • 479
    • 480
    • 481
    • 482
    • 483
    • 484
    • 485
    • 486
    • 487
    • 488
    • 489
    • 490
    • 491
    • 492
    • 493
    • 494
    • 495
    • 496
    • 497
    • 498
    • 499
    • 500
    • 501
    • 502
    • 503
    • 504
    • 505
    • 506
    • 507
    • 508
    • 509
    • 510
    • 511
    • 512
    • 513
    • 514
    • 515
    • 516
    • 517
    • 518
    • 519
    • 520
    • 521
    • 522
    • 523
    • 524
    • 525
    • 526
    • 527
    • 528
    • 529
    • 530
    • 531
    • 532
    • 533
    • 534
    • 535
    • 536
    • 537
    • 538
    • 539
    • 540
    • 541
    • 542
    • 543
    • 544
    • 545
    • 546
    • 547
    • 548
    • 549
    • 550
    • 551
    • 552
    • 553
    • 554
    • 555
    • 556
    • 557
    • 558
    • 559
    • 560
    • 561
  • 相关阅读:
    stm32的ADC采样率如何通过Time定时器进行控制
    NLP工具集:【doccano】——标注平台doccano使用手册
    学过的汇编指令整合
    SWT/Jface(1): 表格的创建和渲染
    IP地址简介
    【计算机网络笔记】网络应用进程通信
    acwing算法提高之图论--最小生成树的扩展应用
    性能优化:Redis使用优化(1)
    Java项目:JSP游戏购买网站
    设计模式-状态模式 golang实现
  • 原文地址:https://blog.csdn.net/ZN175623/article/details/127607154