Java中RedisUtils工具类的使用
前言
本文将提供一个redis的工具类,可以用在Spring Boot以及spring cloud项目中,本工具类主要整合了将Redis作为NoSQL DB使用时的常用方法,以StringRedisTemplate实例为基础,封装了读取、写入、批量写入多个Redis hash等方法,降低了Redis学习成本,使业务代码更加高效、简洁、优雅。
一.pom.xml引入所需依赖
本依赖主要用于使用HashMultimap,该HashMap是java中的HashMap增强版,可以允许键值对中的key重复,此种特性可以用于Redis批量更新hash。后文详细讲述。
<dependency>
<groupId>com.Google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.0-jre</version>
</dependency>
二.RedisUtils工具类
直接上源码,CV工程师必备,新建个Class,将其命名为RedisUtils ,后将首行包名修改下即可使用。
package com.xxx.utils;
import com.google.common.collect.HashMultimap;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class RedisUtils {
private StringRedisTemplate redisTemplate;
public RedisUtils(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public boolean set(final String key, String value) {
boolean result = false;
try {
ValueOperations<String, String> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public boolean set(final String key, String value, Long expireTime) {
boolean result = false;
try {
ValueOperations<String, String> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public void removeByKeys(final String... keys) {
for (String key : keys) {
remove(key);
}
}
public void removePattern(final String pattern) {
Set<String> keys = redisTemplate.keys(pattern);
if (keys != null && keys.size() > 0)
redisTemplate.delete(keys);
}
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
public Boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
public String get(final String key) {
String result = null;
ValueOperations<String, String> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
public void hmSet(String key, String hashKey, String value) {
HashOperations<String, String, String> hash = redisTemplate.opsForHash();
hash.put(key, hashKey, value);
}
public String hmGet(String key, String hashKey) {
HashOperations<String, String, String> hash = redisTemplate.opsForHash();
return hash.get(key, hashKey);
}
public boolean hmHasKey(String key, String hashKey) {
HashOperations<String, String, String> hash = redisTemplate.opsForHash();
return hash.hasKey(key, hashKey);
}
public long hmRemove(String key, String... hashKeys) {
HashOperations<String, String, String> hash = redisTemplate.opsForHash();
return hash.delete(key, hashKeys);
}
public Map<String, String> hashMapGet(String key) {
HashOperations<String, String, String> hash = redisTemplate.opsForHash();
return hash.entries(key);
}
public void hashMapSet(String key, Map<String, String> map) {
HashOperations<String, String, String> hash = redisTemplate.opsForHash();
hash.putAll(key, map);
}
public void lPush(String key, String value) {
ListOperations<String, String> list = redisTemplate.opsForList();
list.rightPush(key, value);
}
public List<String> lRange(String key, long start, long end) {
ListOperations<String, String> list = redisTemplate.opsForList();
return list.range(key, start, end);
}
public void add(String key, String value) {
SetOperations<String, String> set = redisTemplate.opsForSet();
set.add(key, value);
}
public Set<String> setMembers(String key) {
SetOperations<String, String> set = redisTemplate.opsForSet();
return set.members(key);
}
public void zAdd(String key, String value, double score) {
ZSetOperations<String, String> zSet = redisTemplate.opsForZSet();
zSet.add(key, value, score);
}
public Set<String> rangeByScore(String key, double startScore, double endScore) {
ZSetOperations<String, String> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, startScore, endScore);
}
public Set<String> keys(String pattern) {
return redisTemplate.keys(pattern);
}
public List hashMapList(Collection<String> keySet) {
return redisTemplate.executePipelined(new SessionCallback<String>() {
@Override
public <K, V> String execute(RedisOperations<K, V> operations) throws DataAccessException {
HashOperations hashOperations = operations.opsForHash();
for (String key : keySet) {
hashOperations.entries(key);
}
return null;
}
});
}
public void batchHashMapSet(HashMultimap<String, Map<String, String>> batchMap) {
// 设置5秒超时时间
redisTemplate.expire("max", 25, TimeUnit.SECONDS);
redisTemplate.executePipelined(new RedisCallback<List<Map<String, String>>>() {
@Override
public List<Map<String, String>> doInRedis(RedisConnection connection) throws DataAccessException {
Iterator<Map.Entry<String, Map<String, String>>> iterator = batchMap.entries().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Map<String, String>> hash = iterator.next();
// 哈希名,即表名
byte[] hashName = redisTemplate.getStringSerializer().serialize(hash.geTKEy());
Map<String, String> hashValues = hash.getValue();
Iterator<Map.Entry<String, String>> it = hashValues.entrySet().iterator();
// 将元素序列化后缓存,即表的多条哈希记录
Map<byte[], byte[]> hashes = new HashMap<byte[], byte[]>();
while (it.hasNext()) {
// hash中一条key-value记录
Map.Entry<String, String> entry = it.next();
byte[] key = redisTemplate.getStringSerializer().serialize(entry.getKey());
byte[] value = redisTemplate.getStringSerializer().serialize(entry.getValue());
hashes.put(key, value);
}
// 批量保存
connection.hMSet(hashName, hashes);
}
return null;
}
});
}
public void batchHashMapSet(Map<String, Map<String, String>> dataMap) {
// 设置5秒超时时间
redisTemplate.expire("max", 25, TimeUnit.SECONDS);
redisTemplate.executePipelined(new RedisCallback<List<Map<String, String>>>() {
@Override
public List<Map<String, String>> doInRedis(RedisConnection connection) throws DataAccessException {
Iterator<Map.Entry<String, Map<String, String>>> iterator = dataMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Map<String, String>> hash = iterator.next();
// 哈希名,即表名
byte[] hashName = redisTemplate.getStringSerializer().serialize(hash.getKey());
Map<String, String> hashValues = hash.getValue();
Iterator<Map.Entry<String, String>> it = hashValues.entrySet().iterator();
// 将元素序列化后缓存,即表的多条哈希记录
Map<byte[], byte[]> hashes = new HashMap<byte[], byte[]>();
while (it.hasNext()) {
// hash中一条key-value记录
Map.Entry<String, String> entry = it.next();
byte[] key = redisTemplate.getStringSerializer().serialize(entry.getKey());
byte[] value = redisTemplate.getStringSerializer().serialize(entry.getValue());
hashes.put(key, value);
}
// 批量保存
connection.hMSet(hashName, hashes);
}
return null;
}
});
}
public void batchHashMapListSet(List<Map<String, Map<String, String>>> list) {
// 设置5秒超时时间
redisTemplate.expire("max", 25, TimeUnit.SECONDS);
redisTemplate.executePipelined(new RedisCallback<List<Map<String, String>>>() {
@Override
public List<Map<String, String>> doInRedis(RedisConnection connection) throws DataAccessException {
for (Map<String, Map<String, String>> dataMap : list) {
Iterator<Map.Entry<String, Map<String, String>>> iterator = dataMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Map<String, String>> hash = iterator.next();
// 哈希名,即表名
byte[] hashName = redisTemplate.getStringSerializer().serialize(hash.getKey());
Map<String, String> hashValues = hash.getValue();
Iterator<Map.Entry<String, String>> it = hashValues.entrySet().iterator();
// 将元素序列化后缓存,即表的多条哈希记录
Map<byte[], byte[]> hashes = new HashMap<byte[], byte[]>();
while (it.hasNext()) {
// hash中一条key-value记录
Map.Entry<String, String> entry = it.next();
byte[] key = redisTemplate.getStringSerializer().serialize(entry.getKey());
byte[] value = redisTemplate.getStringSerializer().serialize(entry.getValue());
hashes.put(key, value);
}
// 批量保存
connection.hMSet(hashName, hashes);
}
}
return null;
}
});
}
}
三.如何使用工具类
// 1.注入StringRedisTemplate
@Autowired
private StringRedisTemplate stringRedisTemplate
// 2.new一个工具类对象
RedisUtils redisUtils = new RedisUtils(stringRedisTemplate);
// 3.开心的调用工具类任意方法
Map<String, String> map = redisUtils.hashMapGet(redisKey);
四.工具类中批量更新Redis Hash详解
工具类中batchHashMapSet()重载的方法有两个,特别的是,其中一个方法是支持key值重复的,也就说可以同时更新或写入Redis 键名相同的两个hash,后写入的hash会把先写入的数据覆盖,适合一些实时往Redis同步数据的业务场景。
使用方法:
HashMultimap<String, Map<String, String>> batchMap = HashMultimap.create();
redisUtils.batchHashMapSet(batchMap);
总结
本文提供了支持RedisUtils工具类,可以满足大多数场景把Redis作为Nosql DB来使用的操作。
到此这篇关于Java中RedisUtils工具类的使用的文章就介绍到这了,更多相关Java RedisUtils工具类内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关文章