redisTemplate基础用法
时间: 2024-02-05 13:47:54 浏览: 37
redisTemplate是Spring Data Redis提供的核心组件,它提供了对Redis的常见操作的支持。下面是redisTemplate的基础用法:
1. 注入redisTemplate:
```
@Autowired
private RedisTemplate<String, Object> redisTemplate;
```
2. 设置Redis连接工厂:
```
redisTemplate.setConnectionFactory(redisConnectionFactory);
```
3. 设置key和value的序列化方式:
```
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
```
4. 存储数据:
```
redisTemplate.opsForValue().set(key, value);
```
5. 获取数据:
```
Object value = redisTemplate.opsForValue().get(key);
```
6. 删除数据:
```
redisTemplate.delete(key);
```
7. 判断key是否存在:
```
boolean exists = redisTemplate.hasKey(key);
```
8. 设置key的过期时间:
```
redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
```
9. 执行事务:
```
redisTemplate.multi();
// 执行多个操作
redisTemplate.exec();
```
10. 发布和订阅消息:
```
redisTemplate.convertAndSend(channel, message);
```
需要注意的是,redisTemplate支持的操作不仅限于上述示例,还可以执行其他更多Redis的操作,比如对Hash、列表、集合、有序集合等数据结构的操作。具体可以参考Spring Data Redis的官方文档或者源代码。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)