StringRedisTemplate使用
2020-06-12 本文已影响0人
空尘AI
引入maven坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>1.5.8.RELEASE</version>
</dependency>
application.yml文件中加入Redis配置
spring:
application:
name: knowledge-graph
redis:
port: 6379
host: 110.141.17.80
pool:
max-active: 20
max-idle: 20
min-idle: 1
max-wait: -1
database: 0
在Service类中注入StringRedisTemplate对象
@Resource
private StringRedisTemplate stringRedisTemplate;
RedisTemplate中定义了5种数据结构
//操作字符串
redisTemplate.opsForValue();
//操作hash
redisTemplate.opsForHash();
//操作list
redisTemplate.opsForList();
//操作set
redisTemplate.opsForSet();
//操作有序set
redisTemplate.opsForZSet();
1.操作字符串
stringRedisTemplate.opsForValue().set("蜀国创始人","刘备");
stringRedisTemplate.opsForValue().get("蜀国创始人");
2.操作hash
Map<String,String> map=new HashMap<>();
map.put("军师","诸葛亮");
map.put("猛将1","赵子龙");
stringRedisTemplate.opsForHash().putAll("蜀国",map);
Set<Object> keys = stringRedisTemplate.opsForHash().keys("蜀国");
List<Object> values = stringRedisTemplate.opsForHash().values("蜀国");
Object value = stringRedisTemplate.opsForHash().get("蜀国","军师");
3.操作list
// 左侧写入
stringRedisTemplate.opsForList().leftPush("key", "value");
// 获取队列大小
long queueSize = stringRedisTemplate.opsForList().size("key");
// 从右侧取元素
String str = stringRedisTemplate.opsForList().rightPop("key");
4.操作set
// 添加元素
stringRedisTemplate.opsForSet().add("word_cloud","刘德华");
// 获取set集合
Set<String> set = stringRedisTemplate.opsForSet().members("word_cloud");