0
点赞
收藏
分享

微信扫一扫

springboot中操作redis的类StringRedisTemplate


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();   //操作hash
redisTemplate.opsForList();   //操作list
redisTemplate.opsForSet();   //操作set
redisTemplate.opsForZSet();   //操作有序set

3.使用举例

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringbootredisApplication.class)
public class RedisTestForString {

/**注入stringRedisTemplate模板*/
@Autowired
private StringRedisTemplate redisStringTemplate;


@Test
public void testStringRedisTemplateForString() {
/**添加一个key*/
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++");
/**获取key对应的值*/
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");



举报

相关推荐

0 条评论