该文章是接上一篇文章《Redis整合SpringBoot示例》的后续,操作用例代码比较多,这里展示核心代码所占篇幅很多,所以单独抽出来写
set类型在SpringBoot中的使用代码如下
package com.example.echo.redis;
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.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author XLecho
* Date 2019/11/9 0009
* Time 13:36
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTypeSetUseTest {
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
* 在set中添加a b c
*/
@Test
public void testSaddSet() {
redisTemplate.opsForSet().add("mySet", "d", "e", "f");
System.out.println(redisTemplate.opsForSet().members("mySet"));
}
/**
* 获取set的长度
*/
@Test
public void testScardSet() {
System.out.println(redisTemplate.opsForSet().size("mySet"));
}
/**
* 随机获取set集合中的元素
*/
@Test
public void testSrandmemberSet() {
System.out.println(redisTemplate.opsForSet().randomMember("mySet"));
System.out.println(redisTemplate.opsForSet().members("mySet"));
}
/**
* 随机弹出set集合中的元素,弹出的元素会在set集合中删除
*/
@Test
public void testSpopSet() {
System.out.println(redisTemplate.opsForSet().pop("mySet"));
System.out.println(redisTemplate.opsForSet().members("mySet"));
}
/**
* 移除set集合中指定元素
*/
@Test
public void testSremSet() {
redisTemplate.opsForSet().remove("mySet", "b");
System.out.println(redisTemplate.opsForSet().members("mySet"));
}
/**
* 查看元素c是否存在set集合中,存在返回true,不存在返回false
*/
@Test
public void testSismemberSet() {
System.out.println(redisTemplate.opsForSet().isMember("mySet", "c"));
}
/**
* 获取两个集合的差集
*/
@Test
public void testSdiffSet() {
redisTemplate.opsForSet().add("mySet1","a", "b", "c", "d", "e");
redisTemplate.opsForSet().add("mySet2", "c", "d", "e", "f", "g");
System.out.println(redisTemplate.opsForSet().difference("mySet1", "mySet2"));
}
/**
* 获取两个集合的交集
*/
@Test
public void testSinterSet() {
redisTemplate.opsForSet().add("mySet1","a", "b", "c", "d", "e");
redisTemplate.opsForSet().add("mySet2", "c", "d", "e", "f", "g");
System.out.println(redisTemplate.opsForSet().intersect("mySet1", "mySet2"));
}
/**
* 获取两个集合的并集
*/
@Test
public void testSunionSet() {
redisTemplate.opsForSet().add("mySet1","a", "b", "c", "d", "e");
redisTemplate.opsForSet().add("mySet2", "c", "d", "e", "f", "g");
System.out.println(redisTemplate.opsForSet().union("mySet1", "mySet2"));
}
}