目录
1. 添加依赖
2. 配置连接信息
3. 配置 RedisConnectionFactory 和 RedisTemplate
4.在Java中操作Redis
4.1. String 类型操作
4.2 List 类型操作
4.3 Set 类型操作
4.4 Hash类型操作
4.5 sorted set类型操作
Spring Data Redis 是 Spring Data 项目的一部分,它为 Java 应用程序提供了在 Spring 环境中与 Redis 数据库进行交互的便捷方式。通过 Spring Data Redis,可以利用自动配置、模板类(RedisTemplate)、Repository 接口以及对 Redis 数据结构的支持来简化开发工作。
1. 添加依赖
在 Maven 或 Gradle 构建文件中添加 Spring Data Redis 依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 配置连接信息
# application.yml
spring:
redis:
host: localhost
port: 6379
3. 配置 RedisConnectionFactory 和 RedisTemplate
Spring Boot 自动配置会创建一个 RedisConnectionFactory 实例和默认的 RedisTemplate。如果需要自定义序列化器或配置其他选项,可以自己配置:文章来源:https://www.toymoban.com/news/detail-802082.html
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// 设置 key 和 value 的序列化器
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(objectMapper);
StringRedisSerializer stringSerializer = new StringRedisSerializer();
// key 采用 String 序列化
template.setKeySerializer(stringSerializer);
// hash 的 key 也采用 String 序列化
template.setHashKeySerializer(stringSerializer);
// value 采用 JSON 序列化
template.setValueSerializer(serializer);
// hash 的 value 采用 JSON 序列化
template.setHashValueSerializer(serializer);
return template;
}
}
文章来源地址https://www.toymoban.com/news/detail-802082.html
4.在Java中操作Redis
4.1. String 类型操作
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
@Autowired
private StringRedisTemplate redisTemplate;
// 1. 设置(保存)字符串值
public void setStringValue(String key, String value) {
ValueOperations<String, String> operations = redisTemplate.opsForValue();
operations.set(key, value);
}
// 2. 获取字符串值
public String getStringValue(String key) {
ValueOperations<String, String> operations = redisTemplate.opsForValue();
return operations.get(key);
}
// 3. 自增操作(如果key不存在,则默认设置为0再进行自增)
public Long increment(String key) {
return redisTemplate.opsForValue().increment(key);
}
// 4. 自减操作
public Long decrement(String key) {
return redisTemplate.opsForValue().decrement(key);
}
// 5. 设置带过期时间的键值对
public void setExpiryKeyValue(String key, String value, long timeout, TimeUnit timeUnit) {
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
// 6. 获取字符串长度
public Long stringLength(String key) {
return redisTemplate.opsForValue().size(key);
}
// 7. 追加字符串到已存在的key后
public Long appendToKey(String key, String value) {
return redisTemplate.opsForValue().append(key, value);
}
4.2 List 类型操作
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// 1. 将元素添加到列表的头部(左侧)
public void addToListHead(String key, Object value) {
ListOperations<String, Object> listOps = redisTemplate.opsForList();
listOps.leftPush(key, value);
}
// 2. 将元素添加到列表的尾部(右侧)
public void addToListTail(String key, Object value) {
ListOperations<String, Object> listOps = redisTemplate.opsForList();
listOps.rightPush(key, value);
}
// 3. 从列表头部弹出一个元素并返回
public Object popFromListHead(String key) {
ListOperations<String, Object> listOps = redisTemplate.opsForList();
return listOps.leftPop(key);
}
// 4. 从列表尾部弹出一个元素并返回
public Object popFromListTail(String key) {
ListOperations<String, Object> listOps = redisTemplate.opsForList();
return listOps.rightPop(key);
}
// 5. 获取列表指定范围内的元素(左闭右开区间 [start, end))
public List<Object> getRangeFromList(String key, long start, long end) {
ListOperations<String, Object> listOps = redisTemplate.opsForList();
return listOps.range(key, start, end);
}
// 6. 删除列表中与给定值相等的所有元素
public Long removeElementsByValueFromList(String key, Object value) {
ListOperations<String, Object> listOps = redisTemplate.opsForList();
return listOps.remove(key, 0, value); // 参数0表示删除所有匹配项
}
// 7. 在列表的某个索引位置插入元素
public void insertElementAtPosition(String key, int index, Object value) {
ListOperations<String, Object> listOps = redisTemplate.opsForList();
listOps.set(key, index, value);
}
4.3 Set 类型操作
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.RedisTemplate;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// 1. 添加元素到集合中(如果元素已存在,则不添加)
public Long addToSet(String key, Object... values) {
SetOperations<String, Object> setOps = redisTemplate.opsForSet();
return setOps.add(key, values);
}
// 2. 从集合中移除指定元素
public Long removeFromSet(String key, Object... values) {
SetOperations<String, Object> setOps = redisTemplate.opsForSet();
return setOps.remove(key, values);
}
// 3. 判断元素是否存在于集合中
public Boolean isMemberOfSet(String key, Object value) {
SetOperations<String, Object> setOps = redisTemplate.opsForSet();
return setOps.isMember(key, value);
}
// 4. 获取集合中的所有元素
public Set<Object> getMembersFromSet(String key) {
SetOperations<String, Object> setOps = redisTemplate.opsForSet();
return setOps.members(key);
}
// 5. 计算两个集合的交集,并存储到新的key中
public Long intersectAndStoreSets(String destinationKey, String... keys) {
SetOperations<String, Object> setOps = redisTemplate.opsForSet();
return setOps.intersectAndStore(destinationKey, keys);
}
// 6. 计算两个集合的并集,并存储到新的key中
public Long unionAndStoreSets(String destinationKey, String... keys) {
SetOperations<String, Object> setOps = redisTemplate.opsForSet();
return setOps.unionAndStore(destinationKey, keys);
}
// 7. 计算两个集合的差集,并存储到新的key中
public Long differenceAndStoreSets(String destinationKey, String key1, String key2) {
SetOperations<String, Object> setOps = redisTemplate.opsForSet();
return setOps.differenceAndStore(destinationKey, Collections.singletonList(key1), Collections.singletonList(key2));
}
4.4 Hash类型操作
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// 1. 设置Hash中的字段值
public void setHashField(String key, String field, Object value) {
HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
hashOps.put(key, field, value);
}
// 2. 获取Hash中指定字段的值
public Object getHashFieldValue(String key, String field) {
HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
return hashOps.get(key, field);
}
// 3. 获取整个Hash的所有字段和值
public Map<Object, Object> getAllHashFields(String key) {
HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
return hashOps.entries(key);
}
// 4. 删除Hash中一个或多个字段
public Long deleteHashFields(String key, Object... fields) {
HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
return hashOps.delete(key, fields);
}
// 5. 判断Hash中是否存在某个字段
public Boolean hasHashField(String key, String field) {
HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
return hashOps.hasKey(key, field);
}
// 6. 批量设置多个字段值
public void putAllInHash(String key, Map<String, Object> map) {
HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
hashOps.putAll(key, map);
}
4.5 sorted set类型操作
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// 1. 向有序集合添加成员并设置分数
public Long addToSortedSet(String key, Object value, double score) {
ZSetOperations<String, Object> zSetOps = redisTemplate.opsForZSet();
return zSetOps.add(key, value, score);
}
// 2. 根据分数范围获取有序集合中的成员
public Set<Object> getRangeFromSortedSetByScore(String key, double min, double max) {
ZSetOperations<String, Object> zSetOps = redisTemplate.opsForZSet();
return zSetOps.rangeByScore(key, min, max);
}
// 3. 获取有序集合中指定索引范围内的成员
public Set<Object> getRangeFromSortedSet(String key, long start, long end) {
ZSetOperations<String, Object> zSetOps = redisTemplate.opsForZSet();
return zSetOps.range(key, start, end);
}
// 4. 删除有序集合中的指定成员
public Long removeFromSortedSet(String key, Object... values) {
ZSetOperations<String, Object> zSetOps = redisTemplate.opsForZSet();
return zSetOps.remove(key, values);
}
// 5. 获取有序集合中成员的分数
public Double getScoreInSortedSet(String key, Object value) {
ZSetOperations<String, Object> zSetOps = redisTemplate.opsForZSet();
return zSetOps.score(key, value);
}
// 6. 更新有序集合中成员的分数
public Long updateScoreInSortedSet(String key, Object value, double newScore) {
ZSetOperations<String, Object> zSetOps = redisTemplate.opsForZSet();
return zSetOps.incrementScore(key, value, newScore - zSetOps.score(key, value)); // 增量更新,避免多次查询
}
// 7. 计算两个有序集合的交集,并存储到新的key中
public Long intersectAndStoreSortedSets(String destinationKey, String... keys) {
ZSetOperations<String, Object> zSetOps = redisTemplate.opsForZSet();
return zSetOps.intersectAndStore(destinationKey, Arrays.asList(keys));
}
// 8. 计算两个有序集合的并集,并存储到新的key中
public Long unionAndStoreSortedSets(String destinationKey, String... keys) {
ZSetOperations<String, Object> zSetOps = redisTemplate.opsForZSet();
return zSetOps.unionAndStore(destinationKey, Arrays.asList(keys));
}
到了这里,关于Spring Data Redis 在Java中操作Redis的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!