简述
String Redis Template是Spring Data Redis提供的一个模板类,用于简化对Redis数据库的操作,特别是当数据存储为字符串格式时。
依赖引入
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
|
配置文件
1 2 3 4 5 6
| spring: data: redis: host: localhost port: 6379 database: 0
|
使用方法1(值为字符串格式)
设置值
1 2 3 4 5 6 7 8 9 10
| @Service public class RedisService {
@Autowired private StringRedisTemplate stringRedisTemplate;
public void setValue(String key, String value) { stringRedisTemplate.opsForValue().set(key, value); } }
|
获取值
1 2 3
| public String getValue(String key) { return stringRedisTemplate.opsForValue().get(key); }
|
删除键
1 2 3 4
| public void deleteValue(String key) { stringRedisTemplate.delete(key); }
|
使用方法2(值为hash格式)
设置值
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Service public class RedisService {
@Autowired private StringRedisTemplate stringRedisTemplate; // 获取 HashOperations 对象 private HashOperations<String, String, String> hashOps;
// 添加哈希项 public void putHashValue(String key, String hashKey, String value) { hashOps.put(key, hashKey, value); } }
|
获取值
1 2 3 4 5 6 7 8 9
| // 获取哈希项 public String getHashValue(String key, String hashKey) { return hashOps.get(key, hashKey); }
// 获取整个哈希 public Map<String, String> getAllHashValues(String key) { return hashOps.entries(key); }
|
删除键
1 2 3 4
| // 删除哈希项 public void deleteHashValue(String key, String hashKey) { hashOps.delete(key, hashKey); }
|