知乎专栏 |
ValueOperations<String,String> ops = redisTemplate.opsForValue() redisTemplate.opsForValue().set("name","neo"); redisTemplate.opsForValue().get("name")
设置:redisTemplate.opsForValue().set("hello","Helloworld"); 代码:System.out.println(redisTemplate.opsForValue().get("hello",0,5)); 结果:Hellow 代码:System.out.println(redisTemplate.opsForValue().get("hello",0,-1)); 结果:Helloworld 代码:System.out.println(redisTemplate.opsForValue().get("hello",-3,-1)); 结果:rld
redisTemplate.opsForValue().append("hello","Hello"); System.out.println(redisTemplate.opsForValue().get("hello")); redisTemplate.opsForValue().append("hello","world"); System.out.println(redisTemplate.opsForValue().get("hello")); // 结果:Helloworld
redisTemplate.opsForValue().set("name","neo"); System.out.println(redisTemplate.opsForValue().getAndSet("name","Jerry")); // 结果 neo
redisTemplate.opsForValue().set("key","hello world"); System.out.println(redisTemplate.opsForValue().size("key"));
System.out.println(redisTemplate.opsForValue().setIfAbsent("name","neo")); // name 之前已经存在 false System.out.println(redisTemplate.opsForValue().setIfAbsent("age","11")); // age 之前不存在 true
setIfAbsent 实现分布式锁
boolean static = Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent("lock:order", 1, 1, TimeUnit.DAYS));
Map<String,String> maps = new HashMap<String, String>(); maps.put("multi1","multi1"); maps.put("multi2","multi2"); maps.put("multi3","multi3"); redisTemplate.opsForValue().multiSet(maps); List<String> keys = new ArrayList<String>(); keys.add("multi1"); keys.add("multi2"); keys.add("multi3"); System.out.println(redisTemplate.opsForValue().multiGet(keys));
输出结果
[multi1, multi2, multi3]
为多个键分别设置它们的值,如果存在则返回false,不存在返回true
Map<String,String> maps = new HashMap<String, String>(); maps.put("multi11","multi11"); maps.put("multi22","multi22"); maps.put("multi33","multi33"); Map<String,String> maps2 = new HashMap<String, String>(); maps2.put("multi1","multi1"); maps2.put("multi2","multi2"); maps2.put("multi3","multi3"); System.out.println(redisTemplate.opsForValue().multiSetIfAbsent(maps)); // 返回 true System.out.println(redisTemplate.opsForValue().multiSetIfAbsent(maps2)); // 返回 false
setBit Boolean setBit(K key, long offset, boolean value); offset 二进制位置(从左向右数) value 位 ture 表示 0,false 表示 1
// 'a' 的ASCII码是 97 转换为二进制是:01100001 // 'b' 的ASCII码是 98 转换为二进制是:01100010 // 'c' 的ASCII码是 99 转换为二进制是:01100011 redisTemplate.opsForValue().set("bitTest","a"); redisTemplate.opsForValue().setBit("bitTest",7, false); // 01100011 redisTemplate.opsForValue().setBit("bitTest",8, true); // 01100010 System.out.println(redisTemplate.opsForValue().get("bitTest")); redisTemplate.opsForValue().setBit("bitTest",8, false); // 01100011 System.out.println(redisTemplate.opsForValue().get("bitTest"));
getBit Boolean getBit(K key, long offset); 获取键对应值的ascii码的在offset处位值
System.out.println(redisTemplate.opsForValue().getBit("bitTest",7));