zoukankan      html  css  js  c++  java
  • java-redis列表数据操作示例(二)

     接上篇博文《java-redis字符类数据操作示例(一)》,redis连接管理类的代码请跳转查看。

    一、列表类型缓存测试类

    public class ListTest {
        /**
         * 主测试方案
         */
        @Test
        public void test() {
            RedisUtil.instance.run(conn -> oper(conn));
            Assert.assertTrue(true);
        }
        /**
         * 测试用的key
         */
        private final String _key = "simm-list";
        /**
         * 字符串操作
         * 
         * @param conn
         */
        private void oper(ShardedJedis conn) {
            System.out.println(MessageFormat.format("key[{0}]存在:{1} ", _key,conn.exists(_key)));
            //列表数据初始化
            String[] arr= "A,B,C,D,E,F,G".split(",");
            conn.lpush(_key, arr);
            conn.rpush(_key, arr);
            print(conn);
            //-- 列表元素删除方法 ------
            //1.直接移除
            conn.lrem(_key, 1, "G");//从左边数,要删除的元素个数,1:删除从左边找到的第一个数据。
            print(conn);
            //2.出栈
            String val = conn.lpop(_key);
            System.out.println(MessageFormat.format("lpop:{0} ", val));
            print(conn);
            //3.排除
            conn.ltrim(_key, 1, 2);//trim方法在这里相当于过滤,符合条件的留下,其他的元素都删除
            print(conn);
            //-- 列表元素的修改 -----
            conn.lset(_key, 0, "first");
            print(conn);
            //conn.del(_key); //删除key值
            conn.expire(_key, 1); //设置改key值1s后过期,过期后redis自动清理该缓存
            System.out.println(MessageFormat.format("key[{0}]存在:{1} ", _key,conn.exists(_key)));
        }
        private void print(ShardedJedis conn){
            System.out.print(MessageFormat.format("{0}元素输出,长度[{1}]:", _key,conn.llen(_key)));
            List<String> list = conn.lrange(_key, 0, -1);
            for (String str : list) {
                System.out.print(MessageFormat.format("{0} ", str));
            }
            System.out.println();
        }
    }

    二、结果输出

      

  • 相关阅读:
    事后诸葛亮
    冲刺总结
    Alpha第十天
    Alpha第八天
    Alpha第九天
    Alpha第六天
    Alpha第七天
    Alpha第五天
    Python之pytesseract模块-实现OCR
    Selenium4 IDE初体验
  • 原文地址:https://www.cnblogs.com/MrSi/p/8478701.html
Copyright © 2011-2022 走看看