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();} }
二、结果输出