<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
配置
#redis?????
spring:
redis:
host: localhost # ip
port: 6379 #端口
# password: 123456 # 有密码就设置密码
lettuce:
pool:
max-active: 8
测试
@SpringBootTest
@RunWith(SpringRunner.class)
public class redis {
@Autowired
private StringRedisTemplate template;
@Test
public void testRedis() {
//String
BoundValueOperations<String, String> name = template.boundValueOps("name");
name.set("常山赵子龙");
System.out.println(name.get());
}
@Test
public void testRedis2() {
//list
BoundListOperations<String, String> list = template.boundListOps("list");
list.leftPush("aa");
list.leftPush("bb");
list.leftPush("cc");
List<String> range = list.range(0, 10);
for (String s : range) {
System.out.println(s);
}
}
@Test
public void testRedis3() {
//set
BoundSetOperations<String, String> set = template.boundSetOps("set");
set.add("aa", "bb", "cc", "aa");
Set<String> members = set.members();
System.out.println(members);
}
@Test
public void testRedis4() {
//hash
BoundHashOperations<String, Object, Object> hash = template.boundHashOps("hash");
hash.put("a", "sss");
System.out.println(hash.get("a"));
}
@Test
public void testRedis5() {
//zset
BoundZSetOperations<String, String> zset = template.boundZSetOps("zset");
zset.add("cxk", 1);
zset.add("sss", 2);
zset.add("qqq", 3);
Set<String> range = zset.range(0, 10);
System.out.println(range);
}
@Test
public void testRedis6() {
//设置过期时间
template.expire("zset", 20, TimeUnit.SECONDS);
}
@Test
public void testRedis7() {
String s = template.randomKey();
System.out.println(s);
}
@Test
public void testRedis8() {
try {
//开启事务
template.setEnableTransactionSupport(true);
//事务
template.multi();
int i = 1 / 0;
template.boundValueOps("age").set("180");
template.boundValueOps("sex").set("女0");
template.exec();
} catch (Exception e) {
e.printStackTrace();
template.discard();
}
}
}