java操作redis庫,開箱即用

application.yml

spring:application:name: demo#Redis相關配置redis:data:# 地址host: localhost# 端口,默認為6379port: 6379# 數據庫索引database: 0# 密碼password:# 連接超時時間timeout: 10slettuce:pool:# 連接池中的最小空閑連接min-idle: 0# 連接池中的最大空閑連接max-idle: 8# 連接池的最大數據庫連接數max-active: 8# #連接池最大阻塞等待時間(使用負值表示沒有限制)max-wait: -1ms

依賴

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>

序列化配置

package com.example.demo.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
public class RedisConfig {//編寫我們自己的配置redisTemplate@Bean@SuppressWarnings("all")public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(redisConnectionFactory);// JSON序列化配置Jackson2JsonRedisSerializer jsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);ObjectMapper objectMapper=new ObjectMapper();objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jsonRedisSerializer.setObjectMapper(objectMapper);// String的序列化StringRedisSerializer stringRedisSerializer=new StringRedisSerializer();//key和hash的key都采用String的序列化方式template.setKeySerializer(stringRedisSerializer);template.setHashKeySerializer(stringRedisSerializer);//value和hash的value都采用jackson的序列化方式template.setValueSerializer(jsonRedisSerializer);template.setHashValueSerializer(jsonRedisSerializer);template.afterPropertiesSet();return template;}
}

工具類

package com.example.demo.utils;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;import java.util.*;
import java.util.concurrent.TimeUnit;/*** spring redis 工具類** @author ruoyi**/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache
{@Autowiredpublic RedisTemplate redisTemplate;/*** 緩存基本的對象,Integer、String、實體類等** @param key 緩存的鍵值* @param value 緩存的值*/public <T> void setCacheObject(final String key, final T value){redisTemplate.opsForValue().set(key, value);}/*** 緩存基本的對象,Integer、String、實體類等** @param key 緩存的鍵值* @param value 緩存的值* @param timeout 時間* @param timeUnit 時間顆粒度*/public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit){redisTemplate.opsForValue().set(key, value, timeout, timeUnit);}/*** 設置有效時間** @param key Redis鍵* @param timeout 超時時間* @return true=設置成功;false=設置失敗*/public boolean expire(final String key, final long timeout){return expire(key, timeout, TimeUnit.SECONDS);}/*** 設置有效時間** @param key Redis鍵* @param timeout 超時時間* @param unit 時間單位* @return true=設置成功;false=設置失敗*/public boolean expire(final String key, final long timeout, final TimeUnit unit){return redisTemplate.expire(key, timeout, unit);}/*** 獲取有效時間** @param key Redis鍵* @return 有效時間*/public long getExpire(final String key){return redisTemplate.getExpire(key);}/*** 判斷 key是否存在** @param key 鍵* @return true 存在 false不存在*/public Boolean hasKey(String key){return redisTemplate.hasKey(key);}/*** 獲得緩存的基本對象。** @param key 緩存鍵值* @return 緩存鍵值對應的數據*/public <T> T getCacheObject(final String key){ValueOperations<String, T> operation = redisTemplate.opsForValue();return operation.get(key);}/*** 刪除單個對象** @param key*/public boolean deleteObject(final String key){return redisTemplate.delete(key);}/*** 刪除集合對象** @param collection 多個對象* @return*/public boolean deleteObject(final Collection collection){return redisTemplate.delete(collection) > 0;}/*** 緩存List數據** @param key 緩存的鍵值* @param dataList 待緩存的List數據* @return 緩存的對象*/public <T> long setCacheList(final String key, final List<T> dataList){Long count = redisTemplate.opsForList().rightPushAll(key, dataList);return count == null ? 0 : count;}/*** 獲得緩存的list對象** @param key 緩存的鍵值* @return 緩存鍵值對應的數據*/public <T> List<T> getCacheList(final String key){return redisTemplate.opsForList().range(key, 0, -1);}/*** 緩存Set** @param key 緩存鍵值* @param dataSet 緩存的數據* @return 緩存數據的對象*/public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet){BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);Iterator<T> it = dataSet.iterator();while (it.hasNext()){setOperation.add(it.next());}return setOperation;}/*** 獲得緩存的set** @param key* @return*/public <T> Set<T> getCacheSet(final String key){return redisTemplate.opsForSet().members(key);}/*** 緩存Map** @param key* @param dataMap*/public <T> void setCacheMap(final String key, final Map<String, T> dataMap){if (dataMap != null) {redisTemplate.opsForHash().putAll(key, dataMap);}}/*** 獲得緩存的Map** @param key* @return*/public <T> Map<String, T> getCacheMap(final String key){return redisTemplate.opsForHash().entries(key);}/*** 往Hash中存入數據** @param key Redis鍵* @param hKey Hash鍵* @param value 值*/public <T> void setCacheMapValue(final String key, final String hKey, final T value){redisTemplate.opsForHash().put(key, hKey, value);}/*** 獲取Hash中的數據** @param key Redis鍵* @param hKey Hash鍵* @return Hash中的對象*/public <T> T getCacheMapValue(final String key, final String hKey){HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();return opsForHash.get(key, hKey);}/*** 獲取多個Hash中的數據** @param key Redis鍵* @param hKeys Hash鍵集合* @return Hash對象集合*/public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys){return redisTemplate.opsForHash().multiGet(key, hKeys);}/*** 刪除Hash中的某條數據** @param key Redis鍵* @param hKey Hash鍵* @return 是否成功*/public boolean deleteCacheMapValue(final String key, final String hKey){return redisTemplate.opsForHash().delete(key, hKey) > 0;}/*** 獲得緩存的基本對象列表** @param pattern 字符串前綴* @return 對象列表*/public Collection<String> keys(final String pattern){return redisTemplate.keys(pattern);}
}

測試類

RedisCache

package com.example.demo.test;import com.example.demo.utils.RedisCache;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;import java.util.*;
import java.util.concurrent.TimeUnit;@SpringBootTest
class RedisCacheTest {@AutowiredRedisCache redisCache;@AutowiredRedisTemplate redisTemplate;private static final String TEST_KEY = "test:list:key";// 1.緩存對象@Testpublic void setObject() {// redisCache.setCacheObject("object","test");// 附帶過期時間redisCache.setCacheObject("object", "test", 10, TimeUnit.SECONDS);}// 2.過期時間@Testpublic void setTimeOut() {redisCache.setCacheObject("object", "test");// 更新過期時間redisCache.expire("object", 100, TimeUnit.SECONDS);// 獲取過期時間System.out.println(redisCache.getExpire("object"));;}// 3.判斷key是否存在@Testpublic void check() {System.out.println(redisCache.hasKey("object"));}// 4.獲取對象@Testpublic void getObject() {System.out.println((String) redisCache.getCacheObject("object"));}// 5.刪除對象/如果傳遞集合就是刪除多個key@Testpublic void deleteObject() {redisCache.setCacheObject("obj", "1");System.out.println((String) redisCache.getCacheObject("obj"));redisCache.deleteObject("obj");System.out.println((String) redisCache.getCacheObject("obj"));}// 6.獲取list對象@Testpublic void getList() {// 1. 準備測試數據List<String> testData = Arrays.asList("item1", "item2", "item3");redisCache.setCacheList(TEST_KEY, testData);// 2. 調用獲取方法List<Object> result = redisCache.getCacheList(TEST_KEY);// 3. 驗證結果for (Object o : result) {System.out.println(o);}}// 7.獲取set對象@Testpublic void getSet() {// 1. 準備測試數據Set<String> set = Set.of("a", "b");redisCache.setCacheSet("TestSet", set);// 2. 調用獲取方法Set<Object> cacheSet = redisCache.getCacheSet("TestSet");// 3. 驗證結果for (Object o : cacheSet) {System.out.println(o);}}// 8.Map@Testpublic void getMap() {// 1. 準備測試數據Map<String, String> stringStringMap = new HashMap<>();stringStringMap.put("name","zww");stringStringMap.put("age","21");redisCache.setCacheMap("TestMap", stringStringMap);// 2. 調用獲取方法Map<String, Object> testMap = redisCache.getCacheMap("TestMap");// 3. 驗證結果System.out.println(testMap.get("name"));System.out.println(testMap.get("age"));}// 9.hash數據 對比map多了一個外層key@Testpublic void getHash() {// 1. 準備測試數據redisCache.setCacheMapValue("hashMap","testHashMap","1");redisCache.setCacheMapValue("hashMap","testHashMap2","2");// 2. 調用獲取方法System.out.println((String) redisCache.getCacheMapValue("hashMap","testHashMap"));System.out.println((String) redisCache.getCacheMapValue("hashMap","testHashMap2"));}}

RedisTemplate

package com.example.demo.test;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.*;import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;@SpringBootTest
public class RedisTemplateTest {@AutowiredRedisTemplate redisTemplate;/*** 操作String類型的數據*/@Testvoid contextLoads() {// redisTemplate.opsForValue().set("mannor" ,"rediaz");String mannor = (String) redisTemplate.opsForValue().get("mannor");System.out.println(mannor);redisTemplate.opsForValue().set("k1", "v1", 10L, TimeUnit.SECONDS);Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent("mannor1", "mannor");System.out.println(aBoolean);}/*** 操作hash類型的數據*/@Testpublic void hashTest() {HashOperations hashOperations = redisTemplate.opsForHash();// 存hashOperations.put("002", "name", "zhangsan");hashOperations.put("002", "age", "20");hashOperations.put("002", "addr", "beijing");// 取Object age = hashOperations.get("002", "age");
//        System.out.println((String) age);// 獲取所有字段Set keys = hashOperations.keys("002");for (Object key : keys) {
//            System.out.println(key);}// 獲得hash結構中的所有值List values = hashOperations.values("002");for (Object value : values) {System.out.println(value);}}/*** 操作list類型的數據*/@Testpublic void listTest() {ListOperations listOperations = redisTemplate.opsForList();// 存listOperations.leftPush("list", "00");listOperations.leftPushAll("list", "01", "02", "03");// 取值List list = listOperations.range("list", 0, -1);for (Object val : list) {System.out.println(val);}System.out.println("------------------------------------------------------------");// 獲取長度來遍歷Long size = listOperations.size("list");for (int i = 0; i < size; i++) {// 出隊列String element = (String) listOperations.rightPop("list");System.out.println(element);}}/*** 操作Set類型的數據*/@Testpublic void testSet() {SetOperations setOperations = redisTemplate.opsForSet();// 存值setOperations.add("myset", "a", "b", "c", "a");// 取值Set<String> myset = setOperations.members("myset");for (String o : myset) {System.out.println(o);}// 刪除成員setOperations.remove("myset", "a", "b");// 取值myset = setOperations.members("myset");for (String o : myset) {System.out.println(o);}}@Testpublic void testZset() {ZSetOperations zSetOperations = redisTemplate.opsForZSet();// 存值zSetOperations.add("myZset", "a", 10.0);zSetOperations.add("myZset", "b", 11.0);zSetOperations.add("myZset", "c", 12.0);zSetOperations.add("myZset", "a", 13.0);// 取值Set<String> myZset = zSetOperations.range("myZset", 0, -1);for (String s : myZset) {System.out.println(s);}// 修改分數zSetOperations.incrementScore("myZset", "b", 20.0);// 取值myZset = zSetOperations.range("myZset", 0, -1);for (String s : myZset) {System.out.println(s);}// 刪除成員zSetOperations.remove("myZset", "a", "b");// 取值myZset = zSetOperations.range("myZset", 0, -1);for (String s : myZset) {System.out.println(s);}}/*** 通用操作,針對不同的數據類型都可以操作*/@Testpublic void testCommon() {// 獲取Redis中所有的keySet<String> keys = redisTemplate.keys("*");for (String key : keys) {System.out.println(key);}// 判斷某個key是否存在Boolean itcast = redisTemplate.hasKey("itcast");System.out.println(itcast);// 刪除指定keyredisTemplate.delete("myZset");// 獲取指定key對應的value的數據類型DataType dataType = redisTemplate.type("myset");System.out.println(dataType.name());}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/901432.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/901432.shtml
英文地址,請注明出處:http://en.pswp.cn/news/901432.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Cribl 通過Splunk search collector 來收集數據

今天利用Spliunk search collector 來收集數據啦:還是要先cribl 的官方文檔: Splunk Search Collector | Cribl Docs Splunk Search Collector Cribl Stream supports collecting search results from Splunk queries. The queries can be both simple and complex, as well a…

What Was the “Game Genie“ Cheat Device, and How Did It Work?

什么是“Game Genie”作弊裝置&#xff0c;它是如何工作的&#xff1f; First released in 1991, the Game Genie let players enter special codes that made video games easier or unlocked other functions. Nintendo didnt like it, but many gamers loved it. Heres wha…

位運算題目:連接連續二進制數字

文章目錄 題目標題和出處難度題目描述要求示例數據范圍 解法思路和算法代碼復雜度分析 題目 標題和出處 標題&#xff1a;連接連續二進制數字 出處&#xff1a;1680. 連接連續二進制數字 難度 5 級 題目描述 要求 給定一個整數 n \texttt{n} n&#xff0c;將 1 \text…

第十六屆藍橋杯Java b組(試題C:電池分組)

問題描述&#xff1a; 輸入格式&#xff1a; 輸出格式&#xff1a; 樣例輸入&#xff1a; 2 3 1 2 3 4 1 2 3 4 樣例輸出: YES NO 說明/提示 評測用例規模與約定 對于 30% 的評測用例&#xff0c;1≤T≤10&#xff0c;2≤N≤100&#xff0c;1≤Ai?≤10^3。對于 100…

63. 評論日記

2025年4月14日18:53:30 雷軍這次是真的累了_嗶哩嗶哩_bilibili

電商中的訂單支付(內網穿透)

支付頁面 接口文檔 Operation(summary"獲取訂單信息") GetMapping("auth/{orderId}") public Reuslt<OrderInfo> getOrderInfo(Parameter(name"orderId",description"訂單id",requiredtrue) PathVaariable Long orderId){OrderI…

MySQL表的使用(4)

首先回顧一下之前所學的增刪查改&#xff0c;這些覆蓋了平時使用的80% 我們上節課中學習到了MySQL的約束 其中Primary key 是主鍵約束&#xff0c;我們今天要學習的是外鍵約束 插入一個表 外鍵約束 父表 子表 這條記錄中classid為5時候&#xff0c;不能插入&#xff1b; 刪除…

Kotlin作用域函數

在 Kotlin 中&#xff0c;.apply 是一個 作用域函數&#xff08;Scope Function&#xff09;&#xff0c;它允許你在一個對象的上下文中執行代碼塊&#xff0c;并返回該對象本身。它的設計目的是為了 對象初始化 或 鏈式調用 時保持代碼的簡潔性和可讀性。 // 不使用 apply va…

C#集合List<T>與HashSet<T>的區別

在C#中&#xff0c;List和HashSet都是用于存儲元素的集合&#xff0c;但它們在內部實現、用途、性能特性以及使用場景上存在一些關鍵區別。 內部實現 List&#xff1a;基于數組實現的&#xff0c;可以包含重復的元素&#xff0c;并且元素是按照添加的順序存儲的。 HashSet&…

Python 實現的運籌優化系統數學建模詳解(最大最小化模型)

一、引言 在數學建模的實際應用里&#xff0c;最大最小化模型是一種極為關鍵的優化模型。它的核心目標是找出一組決策變量&#xff0c;讓多個目標函數值里的最大值盡可能小。該模型在諸多領域&#xff0c;如資源分配、選址規劃等&#xff0c;都有廣泛的應用。本文將深入剖析最大…

數據庫的種類及常見類型

一&#xff0c;數據庫的種類 最常見的數據庫類型分為兩種&#xff0c;關系型數據庫和非關系型數據庫。 二&#xff0c;關系型數據庫介紹 生產環境主流的關系型數據庫有 Oracle、SQL Server、MySQL/MariaDB等。 關系型數據庫在存儲數據時實際就是采用的一張二維表&#xff0…

PE文件(十五)綁定導入表

我們在分析Windows自帶的一些程序時&#xff0c;常常發現有的程序&#xff0c;如notepad&#xff0c;他的IAT表在文件加載內存前已經完成綁定&#xff0c;存儲了函數的地址。這樣做可以使得程序是無需修改IAT表而直接啟動&#xff0c;這時程序啟動速度變快。但這種方式只適用于…

計算機網絡分層模型:架構與原理

前言 計算機網絡通過不同的層次結構來實現通信和數據傳輸&#xff0c;這種分層設計不僅使得網絡更加模塊化和靈活&#xff0c;也使得不同類型的通信能夠順利進行。在網絡協議和通信體系中&#xff0c;最廣為人知的分層模型有 OSI模型 和 TCP/IP模型。這兩種模型分別定義了計算…

Ollama模型顯存管理機制解析與Flask部署方案對比

一、Ollama顯存釋放機制 Ollama部署模型后&#xff0c;顯存占用分為兩種情況&#xff1a; 首次調用后短暫閑置&#xff08;約5分鐘內&#xff09;&#xff1a; ? 釋放KV Cache等中間計算數據&#xff08;約回收30%-50%顯存&#xff09;。 ? 模型權重仍保留在顯存中&#xf…

KWDB創作者計劃—KWDB技術重構:重新定義數據與知識的神經符號革命

引言&#xff1a;數據洪流中的范式危機 在AI算力突破千卡集群、大模型參數量級邁向萬億的時代&#xff0c;傳統數據庫系統正面臨前所未有的范式危機。當GPT-4展現出跨領域推理能力&#xff0c;AlphaFold3突破蛋白質預測精度時&#xff0c;數據存儲系統卻仍在沿用基于關系代數的…

Unified Modeling Language,統一建模語言

UML&#xff08;Unified Modeling Language&#xff0c;統一建模語言&#xff09;是一種標準化的圖形化建模語言&#xff0c;用于可視化、規范和文檔化軟件系統的設計。UML 提供了一套通用的符號和規則&#xff0c;幫助開發者、架構師和團隊成員更好地理解和溝通軟件系統的結構…

IO模式精講總結

一、IO模型概述 Java中的IO模型主要分為BIO&#xff08;同步阻塞IO&#xff09;、NIO&#xff08;同步非阻塞IO&#xff09;和AIO&#xff08;異步非阻塞IO&#xff09;三種。它們分別適用于不同的業務場景&#xff0c;理解其核心機制對高性能網絡編程至關重要。 二、BIO&…

使用pybind11開發c++擴展模塊輸出到控制臺的中文信息顯示亂碼的問題

使用pybind11開發供Python項目使用的C++擴展模塊時,如果在擴展模塊的C++代碼中向控制臺輸出的信息中包含中文,python程序的控制臺很容易出現亂碼。以如下C++擴展框架代碼為例(這是對上一篇文章簡明使用pybind11開發pythonc+擴展模塊教程-CSDN博客中的C++擴展框架代碼進行少量…

通過jstack分析線程死鎖場景

死鎖的四個必要條件&#xff1a;互斥、持有并等待、不可搶占、循環等待。 死鎖場景是兩個線程各自持有某個鎖&#xff0c;并試圖獲取對方持有的鎖&#xff0c;導致互相等待。 創建死鎖示例代碼 package io.renren.controller;import org.springframework.web.bind.annotation…

PyTorch梯度:深度學習的引擎與實戰解析

一、梯度&#xff1a;深度學習中的指南針 1.1 什么是梯度&#xff1f; 梯度是函數在某一點變化率最大的方向及其大小&#xff0c;就像爬山時最陡峭的上坡方向。在深度學習中&#xff0c;梯度告訴我們如何調整神經網絡參數&#xff0c;使損失函數最小化。 1.2 梯度的重要性 …