springboot中操作redis的类StringRedisTemplate
1.使用前置
在springboot 中使用StringRedisTemplate模板比较简单,首先添加依赖jar包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
在yml文件中配置redis的信息
#简单配置
spring:
redis:
#配置使用的数据库
database: 8
#配置host
host: localhost
#配置端口
port: 6381
2.RedisTemplate中定义了5种数据结构操作
redisTemplate.opsForValue();
redisTemplate.opsForHash();
redisTemplate.opsForList();
redisTemplate.opsForSet();
redisTemplate.opsForZSet();
3.使用举例
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringbootredisApplication.class)
public class RedisTestForString {
@Autowired
private StringRedisTemplate redisStringTemplate;
@Test
public void testStringRedisTemplateForString() {
redisStringTemplate.opsForValue().set("java","java");
redisStringTemplate.opsForValue().set("1","4");
redisStringTemplate.opsForValue().increment("1");
redisStringTemplate.opsForValue().increment("1",5);
String count=redisStringTemplate.opsForValue().get("1");
redisStringTemplate.opsForValue().getAndSet("java","c++");
String key=redisStringTemplate.opsForValue().get("java");
System.out.println("key:"+key);
System.out.println("自增:"+count);
}
}
1.向redis里存入数据和设置缓存时间
stringRedisTemplate.opsForValue().set("test", "100",60*10,TimeUnit.SECONDS);
2.val做-1操作
stringRedisTemplate.boundValueOps("test").increment(-1);
3.根据key获取缓存中的val
stringRedisTemplate.opsForValue().get("test");
4.val +1
stringRedisTemplate.boundValueOps("test").increment(1);
5.根据key获取过期时间
stringRedisTemplate.getExpire("test");
6.根据key获取过期时间并换算成指定单位
stringRedisTemplate.getExpire("test",TimeUnit.SECONDS);
7.根据key删除缓存
stringRedisTemplate.delete("test");
8.检查key是否存在,返回boolean值
stringRedisTemplate.hasKey("546545");
9.向指定key中存放set集合
stringRedisTemplate.opsForSet().add("red_123", "1","2","3");
10.设置过期时间
stringRedisTemplate.expire("red_123",1000 , TimeUnit.MILLISECONDS);
11.根据key查看集合中是否存在指定数据
stringRedisTemplate.opsForSet().isMember("red_123", "1");
12.根据key获取set集合
stringRedisTemplate.opsForSet().members("red_123");