zoukankan      html  css  js  c++  java
  • redis-springdata-api

    使用StringRedisTempalte操作redis五种数据类型

     spring-data中继承了redisTemplate, 提供redis非切片连接池

    代码github地址: https://github.com/wenbronk/redis-java.git

    package com.iwhere.learn.reids.spring;
    
    import java.util.Date;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.util.concurrent.TimeUnit;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
    import org.springframework.data.redis.connection.DataType;
    import org.springframework.data.redis.core.BoundHashOperations;
    import org.springframework.data.redis.core.BoundListOperations;
    import org.springframework.data.redis.core.BoundSetOperations;
    import org.springframework.data.redis.core.BoundValueOperations;
    import org.springframework.data.redis.core.BoundZSetOperations;
    import org.springframework.data.redis.core.HashOperations;
    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    /**
     * 使用spring 整合redis 操作 redisTemplate 通过bound 对 key进行了绑定操作, 绑定后再次操作无需声明key的值,
     * 直接操作value即可 opsForValue 和 boundValueOps类似, 只是没有绑定key
     * 
     * 但遗憾的是, 对redisSharding的支持并不是太好
     * 
     * @author wenbronk
     * @time 2017年3月24日 下午1:29:21 2017
     */
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
    public class RedisTestSpring {
    
        @Autowired
        private StringRedisTemplate redisTemplate;
    
        /**
         * 测试 对key的操作
         */
        @Test
        public void testkey() {
            String key = "user";
            // 删除key
            redisTemplate.delete(key);
            redisTemplate.expire(key, 30, TimeUnit.HOURS);
      }
              
        /**判断key是否存在
         * @param key
         * @return
         */
        public boolean exists(final String key) {
            return redisTemplate.execute(new RedisCallback() {
                public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                    return connection.exists(key.getBytes());
                }
            });
        }
    /**
         * String 类型的value
         */
        @Test
        public void testBoundValueOps() {
            String key = "user";
            BoundValueOperations<String, String> valueOps = redisTemplate.boundValueOps(key);
    
            // 获取key的名字
            String key2 = valueOps.getKey();
    
            // 获取类型
            DataType type = valueOps.getType();
    
            valueOps.set("vini");
            // 不存在添加, 存在返回false
            Boolean setIfAbsent = valueOps.setIfAbsent("456");
    
            String get = valueOps.get();
            valueOps.append("wenbronk");
            // 获取并set
            String andSet = valueOps.getAndSet("wenbronk");
    
            // 获取角标字符
            String getIndex = valueOps.get(0, 2);
            // 在角标添加
            valueOps.set("123", 0);
    
            // 添加并设置过期时间
            valueOps.set("789", 30, TimeUnit.SECONDS);
        }
    
        /**
         * list 类型的操作
         */
        @Test
        public void testBoundListOps() {
            String key = "testList";
            BoundListOperations<String, String> listOps = redisTemplate.boundListOps(key);
    
            // 获取key的名字
            String key2 = listOps.getKey();
    
            // 获取类型
            DataType type = listOps.getType();
    
            // 左侧先出栈, 正常pop
            listOps.leftPush("cs01", "cs03"); // 在cs03的左侧插入
            listOps.leftPushAll("cs0001", "cs002"); // 批量插入
            listOps.leftPushIfPresent("cs02");
    
            // 右侧入栈
            listOps.rightPush("cs01", "cs03");
            listOps.rightPushAll("cs0001", "cs002");
            listOps.rightPushIfPresent("cs02");
    
            // 出栈
            String leftPop = listOps.leftPop();
            String rightPop = listOps.rightPop();
    
            // 根据角标获取
            String index = listOps.index(2);
            List<String> range = listOps.range(0, -1);
            // 替换角标为2 的数据
            listOps.set(2, "abc");
    
            // 删除过期, 如果有的话
            Boolean boolean1 = listOps.persist();
        }
    
        /**
         * 测试set操作
         */
        @Test
        public void testSetOps() {
            BoundSetOperations<String, String> setOps = redisTemplate.boundSetOps("testSet");
    
            // 获取key的名字
            String key2 = setOps.getKey();
    
            // 获取类型
            DataType type = setOps.getType();
    
            // 添加, 可添加多个, 可变参
            setOps.add("aa", "bcb", "ccc");
    
            // 获取, 顺序可能不一致
            Set<String> members = setOps.members();
            // 随机获取一个
            String randomMember = setOps.randomMember();
            // 随机获取两个, 值可能一样
            List<String> randomMembers = setOps.randomMembers(2);
            // 获取两个不一样的随机数
            Set<String> distinctRandomMembers = setOps.distinctRandomMembers(2);
    
            // 是否包含
            Boolean member = setOps.isMember("aa");
    
            // 长度
            Long size = setOps.size();
    
            // 集合运算
            // 交集, 数据类型一致
            Set<String> intersect = setOps.intersect("setTest1");
            // 并集
            Set<String> union = setOps.union("setTest2");
            // 差集
            Set<String> diff = setOps.diff("setTest2");
    
            // 获取集合后, 存在另一个set里面
            setOps.unionAndStore("setTest2", "unionSet");
        }
    
        /**
         * 测试zset操作, 有序集合
         */
        @Test
        public void testZSetOps() {
            BoundZSetOperations<String, String> zsetOps = redisTemplate.boundZSetOps("testZSet");
    
            // 添加, 并给一个初始分数
            zsetOps.add("abc", 1);
    
            // 获取分数
            Double score = zsetOps.score("abc");
            // 统计分数段内的个数
            zsetOps.count(0, 1);
            // 修改一条记录的分数
            zsetOps.incrementScore("abc", 4);
            // 分数段内的元素
            Set<String> rangeByScore = zsetOps.rangeByScore(1, 4);
    
            // 集合运算
            // 交集存储到testZSET3 里面
            zsetOps.intersectAndStore("testZSET2", "testZSET3");
            // 并集
            zsetOps.unionAndStore("testZSET2", "testZSET4");
    
            // 角标操作, 正序获取
            Set<String> range = zsetOps.range(1, -1);
            // 倒序获取
            Set<String> reverseRange = zsetOps.reverseRange(1, -1);
            // 根据分数获取
            Set<TypedTuple<String>> rangeWithScores = zsetOps.rangeWithScores(0, 4);
    
            // 删除元素
            zsetOps.remove("abc");
            // 删除分数段内的元素
            zsetOps.removeRangeByScore(0, 1);
            // 删除指定区间的元素
            zsetOps.removeRange(1, 4);
        }
    
        /**
         * 测试hash结构的
         */
        @Test
        public void testHash() {
            BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps("testHash");
            //存入, 可一次存入多条
            ops.put("cs01", "123");
            ops.putIfAbsent("cs02", "456");
            
            // tableName的名字
            String key1 = ops.getKey();
            DataType type = ops.getType();
            
            // 获取key值
            String key11 = ops.get("cs01");
    
            // 获取所有的key-value值
            Map<String, String> maps = ops.entries();
            
            // ops.persist();//删除过期(如果有的话)的数据。
            ops.getExpire();
            // 设置生存时间
            ops.expireAt(new Date());// true
            
            // 检查元素是否存在
            ops.hasKey("cs01");// true
    
            Set<String> keys = ops.keys();// 获取所有的key
    
            System.out.println("ops.values():" + ops.values());// 获取所有的value
            
            System.out.println("ops.size():" + ops.size());// 2 获取数量
    
            ops.delete("cs01");// 删除key为cs01的数据
        }
    
        /**
         *  opsForXXX 只是没有绑定key名, 其他操作都一样
         * @param tableName
         */
        @Test
        public void opsForHash(String tableName) {
            System.out.println("==================Hash==============");
            HashOperations<String, Object, Object> ops = redisTemplate.opsForHash();
            ops.put(tableName, "cs01", "123");// 存入数据 ops.putAll(maps); 存入多条数据
            Object key11 = ops.get(tableName, "cs01");
            System.out.println("key11:" + key11);// 获取key的值
    
            ops.putIfAbsent(tableName, "cs02", "456");
            Object key21 = ops.get(tableName, "cs02");
            System.out.println("ops.get(cs02)-key21:" + key21);
    
            Map<Object, Object> maps = ops.entries(tableName);// 获取所有的key-value值
            for (Object key : maps.keySet()) {
                System.out.println("map-key:" + key + "map-value:" + maps.get(key));
            }
            // ops.persist();//删除过期(如果有的话)的数据。
            System.out.println("ops.hasKey(cs01):" + ops.hasKey(tableName, "cs01"));// true
            System.out.println("ops.hasKey(cs02):" + ops.hasKey(tableName, "cs02"));// true
            System.out.println("ops.size():" + ops.size(tableName));// 2
    
            Set<Object> keys = ops.keys(tableName);// 获取所有的key
            for (Object string : keys) {
                System.out.println("ops.keys():" + string);
            }
    
            System.out.println("ops.values():" + ops.values(tableName));// 获取所有的value
            System.out.println("ops.size():" + ops.size(tableName));// 2 获取数量
    
            ops.delete("cs01");// 删除key为cs01的
  • 相关阅读:
    1337语言
    BEEF实战全记录
    MySQL字符集编码设置与PHP显示乱码的解决办法
    设置MySql5.5数据库的字符编码为UTF8,解决中文乱码问题
    如何在BeEF中使用metasploit颠覆你的浏览器
    xss窃取cookie测试
    xss测试代码
    'or'='or'经典漏洞代码分析
    mysql注入漏洞测试网页
    ipc$入侵
  • 原文地址:https://www.cnblogs.com/wenbronk/p/6669269.html
Copyright © 2011-2022 走看看