版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nanruitao10/article/details/85161997
在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
做好上步骤就可以使用了,新建测试类:
@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);
}
}
运行验证一下:
列出StringRedisTemplate对应的redis操作命令
String:StringRedisTemplate.opsForValue.xxx
List:StringRedisTemplate.opsForList.xxx
Hash:StringRedisTemplate.opsForHash.xxx
Set:StringRedisTemplate.opsForSet.xxx
ZSet:StringRedisTemplate.opsForZSet.xxx
关于每个命令的演示就不做了,可以查看源码进行学习,前提是你已经熟悉redis的命令