Java中RedisUtils工具類的使用
前言
本文將提供一個(gè)redis的工具類,可以用在Spring boot以及Spring Cloud項(xiàng)目中,本工具類主要整合了將Redis作為NoSql DB使用時(shí)的常用方法,以StringRedisTemplate實(shí)例為基礎(chǔ),封裝了讀取、寫入、批量寫入多個(gè)Redis hash等方法,降低了Redis學(xué)習(xí)成本,使業(yè)務(wù)代碼更加高效、簡潔、優(yōu)雅。
一.pom.xml引入所需依賴
本依賴主要用于使用HashMultimap,該hashmap是java中的HashMap增強(qiáng)版,可以允許鍵值對中的key重復(fù),此種特性可以用于Redis批量更新hash。后文詳細(xì)講述。
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>30.0-jre</version> </dependency>
二.RedisUtils工具類
直接上源碼,CV工程師必備,新建個(gè)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: 大腦補(bǔ)丁 ?* @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; ?? ?} ?? ?/** ?? ? * 寫入緩存設(shè)置時(shí)效時(shí)間 ?? ? * ?? ? * @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; ?? ?} ?? ?/** ?? ? * 批量刪除對應(yīng)的鍵值對 ?? ? * ?? ? * @param keys Redis鍵名數(shù)組 ?? ? */ ?? ?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,也刪除對應(yīng)的value ?? ? * ?? ? * @param key Redis鍵名 ?? ? */ ?? ?public void remove(final String key) { ?? ??? ?if (exists(key)) { ?? ??? ??? ?redisTemplate.delete(key); ?? ??? ?} ?? ?} ?? ?/** ?? ? * 判斷緩存中是否有對應(yīng)的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); ?? ?} ?? ?/** ?? ? * 哈希獲取數(shù)據(jù) ?? ? * ?? ? * @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中一條或多條數(shù)據(jù) ?? ? * ?? ? * @param key ? ? ?Redis鍵 ?? ? * @param hashKeys 哈希鍵名數(shù)組 ?? ? * @return 刪除數(shù)量 ?? ? */ ?? ?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); ?? ?} ?? ?/** ?? ? * 列表-獲取指定范圍數(shù)據(jù) ?? ? * ?? ? * @param key ? Redis鍵名 ?? ? * @param start 開始行號 ?? ? * @param end ? 結(jié)束行號 ?? ? * @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 ? 結(jié)束序號 ?? ? * @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); ?? ?} ?? ?/** ?? ? * 獲取多個(gè)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; ?? ??? ??? ?} ?? ??? ?}); ?? ?} ?? ?/** ?? ? * 保存多個(gè)哈希表(HashMap)(Redis鍵名可重復(fù)) ?? ? * ?? ? * @param batchMap Map<Redis鍵名,Map<鍵,值>> ?? ? */ ?? ?public void batchHashMapSet(HashMultimap<String, Map<String, String>> batchMap) { ?? ??? ?// 設(shè)置5秒超時(shí)時(shí)間 ?? ??? ?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; ?? ??? ??? ?} ?? ??? ?}); ?? ?} ?? ?/** ?? ? * 保存多個(gè)哈希表(HashMap)(Redis鍵名不可以重復(fù)) ?? ? * ?? ? * @param dataMap Map<Redis鍵名,Map<哈希鍵,哈希值>> ?? ? */ ?? ?public void batchHashMapSet(Map<String, Map<String, String>> dataMap) { ?? ??? ?// 設(shè)置5秒超時(shí)時(shí)間 ?? ??? ?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; ?? ??? ??? ?} ?? ??? ?}); ?? ?} ?? ?/** ?? ? * 保存多個(gè)哈希表(HashMap)列表(哈希map的Redis鍵名不能重復(fù)) ?? ? * ?? ? * @param list Map<Redis鍵名,Map<哈希鍵,哈希值>> ?? ? * @see RedisUtils*.batchHashMapSet()* ?? ? */ ?? ?public void batchHashMapListSet(List<Map<String, Map<String, String>>> list) { ?? ??? ?// 設(shè)置5秒超時(shí)時(shí)間 ?? ??? ?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一個(gè)工具類對象 RedisUtils redisUtils = new RedisUtils(stringRedisTemplate); // 3.開心的調(diào)用工具類任意方法 Map<String, String> map = redisUtils.hashMapGet(redisKey);
四.工具類中批量更新Redis Hash詳解
工具類中batchHashMapSet()重載的方法有兩個(gè),特別的是,其中一個(gè)方法是支持key值重復(fù)的,也就說可以同時(shí)更新或?qū)懭隦edis 鍵名相同的兩個(gè)hash,后寫入的hash會把先寫入的數(shù)據(jù)覆蓋,適合一些實(shí)時(shí)往Redis同步數(shù)據(jù)的業(yè)務(wù)場景。
使用方法:
HashMultimap<String, Map<String, String>> batchMap = HashMultimap.create(); redisUtils.batchHashMapSet(batchMap);
總結(jié)
本文提供了支持RedisUtils工具類,可以滿足大多數(shù)場景把Redis作為NoSQL DB來使用的操作。
到此這篇關(guān)于Java中RedisUtils工具類的使用的文章就介紹到這了,更多相關(guān)Java RedisUtils工具類內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Java使用RedisTemplate如何根據(jù)前綴獲取key列表
- Redis五種數(shù)據(jù)結(jié)構(gòu)在JAVA中如何封裝使用
- 使用Java實(shí)現(xiàn)Redis限流的方法
- IDEA版使用Java操作Redis數(shù)據(jù)庫的方法
- JAVA中 redisTemplate 和 jedis的配合使用操作
- Java簡單使用redis-zset實(shí)現(xiàn)排行榜
- Java使用RedisTemplate模糊刪除key操作
- Java使用Redis實(shí)現(xiàn)秒殺功能
- 在Java中使用redisTemplate操作緩存的方法示例
- Java與SpringBoot對redis的使用方式
相關(guān)文章
IDEA與模擬器安裝調(diào)試失敗的處理方法:INSTALL_PARSE_FAILED_NO_CERTIFICATES
這篇文章主要介紹了IDEA與模擬器安裝調(diào)試失敗的處理方法:INSTALL_PARSE_FAILED_NO_CERTIFICATES,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09Java實(shí)踐練習(xí)輕松幾行實(shí)現(xiàn)追書神器
讀萬卷書不如行萬里路,只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用Java實(shí)現(xiàn)一個(gè)追書神器,用技術(shù)改變生活,大家可以在過程中查缺補(bǔ)漏,提升水平2021-10-10如何將maven項(xiàng)目導(dǎo)出jar包(最簡單方法)
大家都知道對于將maven項(xiàng)目導(dǎo)出jar包有好幾種方式,本文給大家分享一種方式最容易且最方便,感興趣的朋友跟隨小編一起看看吧2023-11-11Java笛卡爾積算法原理與實(shí)現(xiàn)方法詳解
這篇文章主要介紹了Java笛卡爾積算法原理與實(shí)現(xiàn)方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了笛卡爾積算法的原理及java定義與使用笛卡爾積算法的相關(guān)操作技巧,需要的朋友可以參考下2017-12-12Java編程中使用JDBC API連接數(shù)據(jù)庫和創(chuàng)建程序的方法
這篇文章主要介紹了Java編程中使用JDBC API連接數(shù)據(jù)庫和創(chuàng)建程序的基本教程,JDBC是一種用于執(zhí)行SQL語句的Java API,可以為多種關(guān)系數(shù)據(jù)庫提供統(tǒng)一訪問需要的朋友可以參考下2015-12-12Spring MVC 中 短信驗(yàn)證碼功能的實(shí)現(xiàn)方法
短信驗(yàn)證功能在各個(gè)網(wǎng)站應(yīng)用都非常廣泛,那么在springmvc中如何實(shí)現(xiàn)短信驗(yàn)證碼功能呢?今天小編抽時(shí)間給大家介紹下Spring MVC 中 短信驗(yàn)證碼功能的實(shí)現(xiàn)方法,一起看看吧2016-09-09