在springboot中
依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
@SpringBootTest class SpringBootTestApplicationTests { @Resource StringRedisTemplate stringRedisTemplate; @Test void StringRedis() { stringRedisTemplate.opsForValue().set("name", "张三"); //设置过期时间10s stringRedisTemplate.expire("name", 10, TimeUnit.SECONDS); } @Test void ListRedis() { List list = new ArrayList<>(); list.add("aaah"); list.add("bbb3"); list.add("ccc2"); // 所有的集合作为一条数据进行储存 rightPush :从尾部添加 stringRedisTemplate.opsForList().rightPush("list1", list.toString()); // leftPush :从头部添加 stringRedisTemplate.opsForList().leftPush("list2", list.toString()); // 作为n数据进行储存 stringRedisTemplate.opsForList().rightPushAll("list5", list); // list集合获取启始到结束的集合 List<String> list1 = stringRedisTemplate.opsForList().range("list1", 0, -1); List<String> list5 = stringRedisTemplate.opsForList().range("list5", 0, -1); System.out.println("list1 :" + list1); System.out.println("list5 :" + list5); // list1 :[[aaah, bbb3, ccc2], [aaah, bbb3, ccc2]] // list5 :[aaah, bbb3, ccc2, aaah, bbb3, ccc2] } @Test void SetRedis() { // 无序不可以重复的集合 stringRedisTemplate.opsForSet().add("z1a", "aaa", "bbb", "ddd", "ccc", "aaa"); // set获取 Set<String> z1a = stringRedisTemplate.opsForSet().members("z1a"); System.out.println(z1a); // [aaa, bbb, ddd, ccc] // 查看个数 Long z1a1 = stringRedisTemplate.opsForSet().size("z1a"); System.out.println("z1a1:" + z1a1); // z1a1:4 } @Test void ZSetRedis() { // 有序不可以重复的集合 stringRedisTemplate.opsForZSet().add("z1b", "aaa", 22); stringRedisTemplate.opsForZSet().add("z1b", "ccc", 11); stringRedisTemplate.opsForZSet().add("z1b", "ddd", 33); // zset获取 Set<String> z1b = stringRedisTemplate.opsForZSet().range("z1b", 0, -1); System.out.println("z1b:" + z1b); // z1b:[ccc, dd, aaa, bbb, ddd] } @Test void HashRedis() { stringRedisTemplate.opsForHash().put("user", "name", "小明"); stringRedisTemplate.opsForHash().put("user", "pass", "123456"); stringRedisTemplate.opsForHash().put("user", "age", "15"); // 获取单个 Object o = stringRedisTemplate.opsForHash().get("user", "name"); System.out.println("o:" + o); //o:小明 // 获取所有 Map<Object, Object> user = stringRedisTemplate.opsForHash().entries("user"); System.out.println("user:" + user); // user:{name=小明, pass=123456, age=15} } }
标签:springboot,数据类型,redis,list,add,user,println,z1b,stringRedisTemplate From: https://www.cnblogs.com/xbinbin/p/17181284.html