Java中RedisUtils工具類的使用
前言
本文將提供一個redis的工具類,可以用在Spring boot以及Spring Cloud項目中,本工具類主要整合了將Redis作為NoSql DB使用時的常用方法,以StringRedisTemplate實例為基礎,封裝了讀取、寫入、批量寫入多個Redis hash等方法,降低了Redis學習成本,使業(yè)務代碼更加高效、簡潔、優(yōu)雅。
一.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;
/**
?* @description: Redis工具類(String類型)
?* @author: 大腦補丁
?* @create: 2022-06-23 16:02
?*/
public class RedisUtils {
?? ?private StringRedisTemplate redisTemplate;
?? ?public RedisUtils(StringRedisTemplate redisTemplate) {
?? ??? ?this.redisTemplate = redisTemplate;
?? ?}
?? ?/**
?? ? * 寫入緩存
?? ? *
?? ? * @param key ? redis鍵
?? ? * @param value redis值
?? ? * @return 是否成功
?? ? */
?? ?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;
?? ?}
?? ?/**
?? ? * 寫入緩存設置時效時間
?? ? *
?? ? * @param key ? redis鍵
?? ? * @param value redis值
?? ? * @return 是否成功
?? ? */
?? ?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;
?? ?}
?? ?/**
?? ? * 批量刪除對應的鍵值對
?? ? *
?? ? * @param keys Redis鍵名數組
?? ? */
?? ?public void removeByKeys(final String... keys) {
?? ??? ?for (String key : keys) {
?? ??? ??? ?remove(key);
?? ??? ?}
?? ?}
?? ?/**
?? ? * 批量刪除Redis key
?? ? *
?? ? * @param pattern 鍵名包含字符串(如:myKey*)
?? ? */
?? ?public void removePattern(final String pattern) {
?? ??? ?Set<String> keys = redisTemplate.keys(pattern);
?? ??? ?if (keys != null && keys.size() > 0)
?? ??? ??? ?redisTemplate.delete(keys);
?? ?}
?? ?/**
?? ? * 刪除key,也刪除對應的value
?? ? *
?? ? * @param key Redis鍵名
?? ? */
?? ?public void remove(final String key) {
?? ??? ?if (exists(key)) {
?? ??? ??? ?redisTemplate.delete(key);
?? ??? ?}
?? ?}
?? ?/**
?? ? * 判斷緩存中是否有對應的value
?? ? *
?? ? * @param key Redis鍵名
?? ? * @return 是否存在
?? ? */
?? ?public Boolean exists(final String key) {
?? ??? ?return redisTemplate.hasKey(key);
?? ?}
?? ?/**
?? ? * 讀取緩存
?? ? *
?? ? * @param key Redis鍵名
?? ? * @return 是否存在
?? ? */
?? ?public String get(final String key) {
?? ??? ?String result = null;
?? ??? ?ValueOperations<String, String> operations = redisTemplate.opsForValue();
?? ??? ?result = operations.get(key);
?? ??? ?return result;
?? ?}
?? ?/**
?? ? * 哈希 添加
?? ? *
?? ? * @param key ? ? Redis鍵
?? ? * @param hashKey 哈希鍵
?? ? * @param value ? 哈希值
?? ? */
?? ?public void hmSet(String key, String hashKey, String value) {
?? ??? ?HashOperations<String, String, String> hash = redisTemplate.opsForHash();
?? ??? ?hash.put(key, hashKey, value);
?? ?}
?? ?/**
?? ? * 哈希獲取數據
?? ? *
?? ? * @param key ? ? Redis鍵
?? ? * @param hashKey 哈希鍵
?? ? * @return 哈希值
?? ? */
?? ?public String hmGet(String key, String hashKey) {
?? ??? ?HashOperations<String, String, String> hash = redisTemplate.opsForHash();
?? ??? ?return hash.get(key, hashKey);
?? ?}
?? ?/**
?? ? * 判斷hash是否存在鍵
?? ? *
?? ? * @param key ? ? Redis鍵
?? ? * @param hashKey 哈希鍵
?? ? * @return 是否存在
?? ? */
?? ?public boolean hmHasKey(String key, String hashKey) {
?? ??? ?HashOperations<String, String, String> hash = redisTemplate.opsForHash();
?? ??? ?return hash.hasKey(key, hashKey);
?? ?}
?? ?/**
?? ? * 刪除hash中一條或多條數據
?? ? *
?? ? * @param key ? ? ?Redis鍵
?? ? * @param hashKeys 哈希鍵名數組
?? ? * @return 刪除數量
?? ? */
?? ?public long hmRemove(String key, String... hashKeys) {
?? ??? ?HashOperations<String, String, String> hash = redisTemplate.opsForHash();
?? ??? ?return hash.delete(key, hashKeys);
?? ?}
?? ?/**
?? ? * 獲取所有哈希鍵值對
?? ? *
?? ? * @param key Redis鍵名
?? ? * @return 哈希Map
?? ? */
?? ?public Map<String, String> hashMapGet(String key) {
?? ??? ?HashOperations<String, String, String> hash = redisTemplate.opsForHash();
?? ??? ?return hash.entries(key);
?? ?}
?? ?/**
?? ? * 保存Map到哈希
?? ? *
?? ? * @param key Redis鍵名
?? ? * @param map 哈希Map
?? ? */
?? ?public void hashMapSet(String key, Map<String, String> map) {
?? ??? ?HashOperations<String, String, String> hash = redisTemplate.opsForHash();
?? ??? ?hash.putAll(key, map);
?? ?}
?? ?/**
?? ? * 列表-追加值
?? ? *
?? ? * @param key ? Redis鍵名
?? ? * @param value 列表值
?? ? */
?? ?public void lPush(String key, String value) {
?? ??? ?ListOperations<String, String> list = redisTemplate.opsForList();
?? ??? ?list.rightPush(key, value);
?? ?}
?? ?/**
?? ? * 列表-獲取指定范圍數據
?? ? *
?? ? * @param key ? Redis鍵名
?? ? * @param start 開始行號
?? ? * @param end ? 結束行號
?? ? * @return 列表
?? ? */
?? ?public List<String> lRange(String key, long start, long end) {
?? ??? ?ListOperations<String, String> list = redisTemplate.opsForList();
?? ??? ?return list.range(key, start, end);
?? ?}
?? ?/**
?? ? * 集合添加
?? ? *
?? ? * @param key ? Redis鍵名
?? ? * @param value 值
?? ? */
?? ?public void add(String key, String value) {
?? ??? ?SetOperations<String, String> set = redisTemplate.opsForSet();
?? ??? ?set.add(key, value);
?? ?}
?? ?/**
?? ? * 集合獲取
?? ? *
?? ? * @param key Redis鍵名
?? ? * @return 集合
?? ? */
?? ?public Set<String> setMembers(String key) {
?? ??? ?SetOperations<String, String> set = redisTemplate.opsForSet();
?? ??? ?return set.members(key);
?? ?}
?? ?/**
?? ? * 有序集合添加
?? ? *
?? ? * @param key ? Redis鍵名
?? ? * @param value 值
?? ? * @param score 排序號
?? ? */
?? ?public void zAdd(String key, String value, double score) {
?? ??? ?ZSetOperations<String, String> zSet = redisTemplate.opsForZSet();
?? ??? ?zSet.add(key, value, score);
?? ?}
?? ?/**
?? ? * 有序集合-獲取指定范圍
?? ? *
?? ? * @param key ? ? ? ?Redis鍵
?? ? * @param startScore 開始序號
?? ? * @param endScore ? 結束序號
?? ? * @return 集合
?? ? */
?? ?public Set<String> rangeByScore(String key, double startScore, double endScore) {
?? ??? ?ZSetOperations<String, String> zset = redisTemplate.opsForZSet();
?? ??? ?return zset.rangeByScore(key, startScore, endScore);
?? ?}
?? ?/**
?? ? * 模糊查詢Redis鍵名
?? ? *
?? ? * @param pattern 鍵名包含字符串(如:myKey*)
?? ? * @return 集合
?? ? */
?? ?public Set<String> keys(String pattern) {
?? ??? ?return redisTemplate.keys(pattern);
?? ?}
?? ?/**
?? ? * 獲取多個hashMap
?? ? *
?? ? * @param keySet
?? ? * @return List<Map < String, String>> hashMap列表
?? ? */
?? ?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;
?? ??? ??? ?}
?? ??? ?});
?? ?}
?? ?/**
?? ? * 保存多個哈希表(HashMap)(Redis鍵名可重復)
?? ? *
?? ? * @param batchMap Map<Redis鍵名,Map<鍵,值>>
?? ? */
?? ?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;
?? ??? ??? ?}
?? ??? ?});
?? ?}
?? ?/**
?? ? * 保存多個哈希表(HashMap)(Redis鍵名不可以重復)
?? ? *
?? ? * @param dataMap Map<Redis鍵名,Map<哈希鍵,哈希值>>
?? ? */
?? ?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;
?? ??? ??? ?}
?? ??? ?});
?? ?}
?? ?/**
?? ? * 保存多個哈希表(HashMap)列表(哈希map的Redis鍵名不能重復)
?? ? *
?? ? * @param list Map<Redis鍵名,Map<哈希鍵,哈希值>>
?? ? * @see RedisUtils*.batchHashMapSet()*
?? ? */
?? ?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同步數據的業(yè)務場景。
使用方法:
HashMultimap<String, Map<String, String>> batchMap = HashMultimap.create(); redisUtils.batchHashMapSet(batchMap);
總結
本文提供了支持RedisUtils工具類,可以滿足大多數場景把Redis作為NoSQL DB來使用的操作。
到此這篇關于Java中RedisUtils工具類的使用的文章就介紹到這了,更多相關Java RedisUtils工具類內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring遠程調用HttpClient/RestTemplate的方法
這篇文章主要介紹了Spring遠程調用HttpClient/RestTemplate的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03
基于spring-security 401 403錯誤自定義處理方案
這篇文章主要介紹了基于spring-security 401 403錯誤自定義處理方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
String StringBuilder StringBuffer區(qū)別以及源碼分析
string是C++標準庫的一個重要的部分,主要用于字符串處理。可以使用輸入輸出流方式直接進行string操作,同時,C++的算法庫對string類也有著很好的支持,并且string類還和c語言的字符串之間有著良好的接口2021-06-06

