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)版,可以允許鍵值對(duì)中的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;
?? ?}
?? ?/**
?? ? * 批量刪除對(duì)應(yīng)的鍵值對(duì)
?? ? *
?? ? * @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,也刪除對(duì)應(yīng)的value
?? ? *
?? ? * @param key Redis鍵名
?? ? */
?? ?public void remove(final String key) {
?? ??? ?if (exists(key)) {
?? ??? ??? ?redisTemplate.delete(key);
?? ??? ?}
?? ?}
?? ?/**
?? ? * 判斷緩存中是否有對(duì)應(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);
?? ?}
?? ?/**
?? ? * 獲取所有哈希鍵值對(duì)
?? ? *
?? ? * @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 開始行號(hào)
?? ? * @param end ? 結(jié)束行號(hào)
?? ? * @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 排序號(hào)
?? ? */
?? ?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 開始序號(hào)
?? ? * @param endScore ? 結(jié)束序號(hào)
?? ? * @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è)工具類對(duì)象 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會(huì)把先寫入的數(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)容請(qǐng)搜索腳本之家以前的文章或繼續(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對(duì)redis的使用方式
相關(guān)文章
Java 讀取網(wǎng)絡(luò)圖片存儲(chǔ)到本地并生成縮略圖
用Java做開發(fā)經(jīng)常需要處理圖片。本文就來看一下如何保存圖片到本地并生成縮略圖2021-05-05
Spring遠(yuǎn)程調(diào)用HttpClient/RestTemplate的方法
這篇文章主要介紹了Spring遠(yuǎn)程調(diào)用HttpClient/RestTemplate的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03
基于spring-security 401 403錯(cuò)誤自定義處理方案
這篇文章主要介紹了基于spring-security 401 403錯(cuò)誤自定義處理方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
Java 入門圖形用戶界面設(shè)計(jì)之列表框JList
圖形界面(簡稱GUI)是指采用圖形方式顯示的計(jì)算機(jī)操作用戶界面。與早期計(jì)算機(jī)使用的命令行界面相比,圖形界面對(duì)于用戶來說在視覺上更易于接受,本篇精講Java語言中關(guān)于圖形用戶界面的列表框JList2022-02-02
String StringBuilder StringBuffer區(qū)別以及源碼分析
string是C++標(biāo)準(zhǔn)庫的一個(gè)重要的部分,主要用于字符串處理??梢允褂幂斎胼敵隽鞣绞街苯舆M(jìn)行string操作,同時(shí),C++的算法庫對(duì)string類也有著很好的支持,并且string類還和c語言的字符串之間有著良好的接口2021-06-06
Windows下gradle的安裝與配置的超詳細(xì)教程
這篇文章主要介紹了Windows下gradle的安裝與配置,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09

