spring-data-redis的使用

1、spring-data-redis

spring-data-redis 是 Spring Data 系列的一部分,它提供了在 Spring 应用中对 Redis 更加容易的配置和访问。

1.1 RedisTemplate

spring-data-redis 中 RedisTemplate 类提供了对 Redis 各种操作。

RedisTemplate 常用APIBoolean delete(K key) 删除
Long delete(Collection<K> keys) 批量删除

Boolean hasKey(K key) 验证指定 key 是否存在	
Set<K> keys(K pattern) 获取符合给定模式的 key 集合 

Boolean expire(K key, long timeout, TimeUnit unit) 设置 key 的过期时间
Boolean persist(K key) 移除给定 key 的过期时间
Long getExpire(K key) 获取指定 key 的过期时间
Long getExpire(K key, TimeUnit timeUnit) 获取指定 key 的过期时间

ValueOperations<K,V> opsForValue() 返回对 string 执行的操作。
<HK,HV> HashOperations<K,HK,HV> opsForHash() 返回对 hash 执行的操作。
ListOperations<K,V> opsForList() 返回对 list 执行的操作。
SetOperations<K,V> opsForSet() 返回对 set 执行的操作。
ZSetOperations<K,V> opsForZSet() 返回对 zset 执行的操作。

其中 opsForValue() 对 string 执行的操作:

V get(Object key) 获取指定 key 的 value 值

V getAndSet(K key, V newValue) 如果 key 存在则覆盖,并返回旧值;如果不存在,返回 null 并添加。

void set(K key, V value) 新增 key-value
void set(K key, V value, final long timeout, final TimeUnit unit) 置 key-value 并添加过期时间
	
Boolean setIfAbsent(K key, V value) 
如果 key 不存在,则设置 key 以保存字符串值。
Boolean setIfAbsent(K key, V value, long timeout, TimeUnit unit) 
如果 key 不存在,则设置 key 以保存字符串值和过期超时。

Long size(K key) 获取存储在 key 中的值的长度。

1.2、StringRedisTemplate

StringRedisTemplate 是 RedisTemplate 以字符串为中心的扩展。由于大多数针对 Redis 的操作都是基于字符串的,因此提供了一个专用类,以最大限度的减少其更通用模板的配置,尤其是在序列化程序方面。

StringRedisTemplate 定义:
package org.springframework.data.redis.core;

import org.springframework.data.redis.connection.DefaultStringRedisConnection;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializer;

public class StringRedisTemplate extends RedisTemplate<String, String> {
    public StringRedisTemplate() {
        this.setKeySerializer(RedisSerializer.string());
        this.setValueSerializer(RedisSerializer.string());
        this.setHashKeySerializer(RedisSerializer.string());
        this.setHashValueSerializer(RedisSerializer.string());
    }

    public StringRedisTemplate(RedisConnectionFactory connectionFactory) {
        this();
        this.setConnectionFactory(connectionFactory);
        this.afterPropertiesSet();
    }

    protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
        return new DefaultStringRedisConnection(connection);
    }
}

参考API文档:https://docs.spring.io/spring-data/redis/docs/current/api/
其中 RedisTemplate 、StringRedisTemplate 都是 org.springframework.data.redis.core 包下的类。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值