Springboot——Redis的使用

在當今的軟件開發領域,緩存技術是提升應用性能的關鍵手段之一。Redis 作為一款高性能的鍵值對存儲數據庫,憑借其出色的讀寫速度和豐富的數據結構,在緩存場景中得到了廣泛應用。Spring Boot 作為一款簡化 Spring 應用開發的框架,與 Redis 的集成可以讓開發者輕松地在項目中使用 Redis 緩存。本文將詳細介紹如何在 Spring Boot 項目中集成和使用 Redis。

項目搭建

首先在你的項目中引入redis的Maven依賴確保使用

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

在?application.properties?或?application.yml?中配置 Redis 連接信息。以下是?application.yml?的示例配置:

spring: redis:database: 0           # Redis服務器數據庫host: 127.0.0.1       # Redis服務器地址port: 6379            # Redis服務器連接端口password: 123456      # Redis服務器連接密碼(默認為空)timeout: 6000         # Redis連接超時時間(毫秒)

Redis 基本操作

配置Redis的配置類

package com.lppaa.redisdemo.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;import java.time.Duration;
import java.util.HashMap;
import java.util.Map;@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {@Beanpublic CacheManager cacheManager(RedisConnectionFactory factory){RedisSerializer<String> keyRedisSerializer = new StringRedisSerializer(); // redis的key序列化方式Jackson2JsonRedisSerializer valueRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); // redis的value的序列化//解決查詢緩存轉換異常的問題ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);valueRedisSerializer.setObjectMapper(om);//配置序列化(解決亂碼的問題)RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ZERO) // 默認生存時間.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keyRedisSerializer)).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueRedisSerializer)).disableCachingNullValues();//緩存配置mapMap<String,RedisCacheConfiguration> cacheConfigurationMap=new HashMap<>();//自定義緩存名,后面使用的@Cacheable的CacheNamecacheConfigurationMap.put("myRedis",config);
//        cacheConfigurationMap.put("default",config);RedisCacheManager cacheManager = RedisCacheManager.builder(factory).cacheDefaults(config).withInitialCacheConfigurations(cacheConfigurationMap).build();return cacheManager;}@Beanpublic RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {StringRedisTemplate template = new StringRedisTemplate(factory);Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(om);template.setValueSerializer(jackson2JsonRedisSerializer);template.afterPropertiesSet();return template;}}
  • CacheManager方法:負責管理緩存的創建、獲取和清理等操作。此方法對 Redis 緩存管理器進行了配置,具體步驟如下:
    • 序列化配置
      • 對 Redis 的鍵使用?StringRedisSerializer?進行序列化。
      • 對 Redis 的值使用?Jackson2JsonRedisSerializer?進行序列化,同時配置?ObjectMapper?以避免查詢緩存時出現轉換異常。
    • 緩存配置
      • 借助?RedisCacheConfiguration?配置默認的緩存策略,包含默認生存時間、鍵和值的序列化方式,并且禁止緩存空值。
      • 創建一個?Map?來存放自定義的緩存配置,這里定義了一個名為?"myRedis"?的緩存。
    • 緩存管理器構建
      • 利用?RedisCacheManager.builder?構建緩存管理器,設置默認緩存配置以及自定義的緩存配置。
  • redisTemplate方法:作用是在代碼里對 Redis 進行操作

    • 采用?StringRedisTemplate?作為基礎模板,它是?RedisTemplate?的子類,專門用于處理字符串類型的鍵和值。
    • 同樣使用?Jackson2JsonRedisSerializer?對值進行序列化,并且配置?ObjectMapper?以防止查詢緩存時出現轉換異常。

編寫服務層邏輯

EmployeeService接口類
public interface EmployeeService {List<Employee> findAll();Employee findById(Integer id);Employee update(Employee employee);Integer delete(Integer id);}

EmployeeServiceImpl接口實現類

package com.lppaa.redisdemo.service.serviceImpl;import com.lppaa.redisdemo.dao.EmployeeDao;
import com.lppaa.redisdemo.entity.Employee;
import com.lppaa.redisdemo.service.EmployeeService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;import java.util.Collections;
import java.util.Date;
import java.util.List;@Service
public class EmployeeServiceImpl implements EmployeeService {@AutowiredEmployeeDao employeeDao;@Overridepublic List<Employee> findAll() {return employeeDao.findAll();}@Override@Cacheable(cacheNames = "myRedis" ,key = "T(com.lppaa.redisdemo.utils.MD5Utils).md5('EmployeeService_findById' + #id)" ,unless = "#result==null")public Employee findById(Integer id) {System.out.println("進入方法,去數據庫查詢");return employeeDao.findById(id);}@Override@CachePut(cacheNames = "myRedis", key = "T(com.lppaa.redisdemo.utils.MD5Utils).md5('EmployeeService_findById' + #employee.id)",condition = "#result != null")public Employee update(Employee employee) {employee.setTime(new Date());Integer ans = employeeDao.update(employee);if(ans>0)return employeeDao.findById(employee.getId());return null;//表示更新失敗 結果為空 不存入緩存 結果不變}@Override@CacheEvict(cacheNames = "myRedis", key = "T(com.lppaa.redisdemo.utils.MD5Utils).md5('EmployeeService_findById' + #id)")public Integer delete(Integer id) {Integer s = employeeDao.delete(id);return s;}
}
@Cacheable?注解?
  • @Cacheable?注解:用于標記該方法的結果可以被緩存。
    • cacheNames = "myRedis":指定使用名為?myRedis?的緩存,這個緩存名稱在?RedisConfig?類中配置。
    • key = "T(com.lppaa.redisdemo.utils.MD5Utils).md5('EmployeeService_findById' + #id)":使用 SpEL(Spring Expression Language)表達式生成緩存的鍵。這里調用?MD5Utils?類的?md5?方法對?"EmployeeService_findById"?和傳入的?id?拼接后的字符串進行 MD5 加密,確保每個不同的?id?對應一個唯一的緩存鍵。
    • unless = "#result==null":表示如果方法的返回結果為?null,則不將結果存入緩存。
  • 當調用該方法時,Spring 會先檢查緩存中是否存在對應的鍵,如果存在則直接返回緩存中的結果,否則執行方法體中的代碼,從數據庫中查詢數據,并將結果存入緩存。
@CachePut?注解
  • @CachePut?注解:用于更新緩存。無論緩存中是否存在對應的鍵,都會執行方法體中的代碼,并將方法的返回結果存入緩存。
    • cacheNames = "myRedis":指定使用名為?myRedis?的緩存。
    • key = "T(com.lppaa.redisdemo.utils.MD5Utils).md5('EmployeeService_findById' + #employee.id)":生成緩存的鍵,與?findById?方法使用相同的鍵生成策略。
    • condition = "#result != null":表示只有當方法的返回結果不為?null?時,才將結果存入緩存。
  • 該方法首先更新員工的時間戳,然后調用?EmployeeDao?的?update?方法更新數據庫中的員工信息。如果更新成功,則再次查詢數據庫獲取最新的員工信息并返回,同時更新緩存;如果更新失敗,則返回?null,不更新緩存。
CacheEvict?注解
  • @CacheEvict?注解:用于從緩存中移除指定鍵的緩存項。
    • cacheNames = "myRedis":指定使用名為?myRedis?的緩存。
    • key = "T(com.lppaa.redisdemo.utils.MD5Utils).md5('EmployeeService_findById' + #id)":生成要移除的緩存鍵,與?findById?和?update?方法使用相同的鍵生成策略。
  • 該方法調用?EmployeeDao?的?delete?方法從數據庫中刪除指定?id?的員工信息,并從緩存中移除對應的緩存項。

編寫控制層邏輯

package com.lppaa.redisdemo.controller;import com.alibaba.fastjson.JSON;
import com.lppaa.redisdemo.entity.Employee;
import com.lppaa.redisdemo.entity.User;
import com.lppaa.redisdemo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;import java.util.Date;@RestController
@RequestMapping("/test")
public class RedisController {@Autowiredprivate RedisTemplate redisTemplate;@Autowiredprivate EmployeeService employeeService;@Autowiredprivate StringRedisTemplate stringRedisTemplate;@RequestMapping("/aaa")public String testA(){User user = new User();user.setName("李四");user.setAge(20);
//        redisTemplate.opsForValue().set("user", JSON.toJSONString(user));//redisTemplate.opsForValue().set("ttt", user);stringRedisTemplate.opsForValue().set("qweirj", JSON.toJSONString(user));return "success";}@RequestMapping("/findbyid")@ResponseBodypublic Employee findbyId(Integer id){Employee employee = employeeService.findById(id);return employee;}@RequestMapping("/update")@ResponseBodypublic String update(Employee e){e.setTime(new Date());Employee byId = employeeService.update(e);if(byId != null)return "success";return "false";}@RequestMapping("/delete")@ResponseBodypublic String dete(Integer id){Integer s = employeeService.delete(id);if(s == 1)return "success";return "false";}
}

最后打開Redis即可進行使用。

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

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

相關文章

BEVPoolv2:A Cutting-edge Implementation of BEVDet Toward Deployment

背景 該論文是在BEVDet的基礎上進行了一個調整優化&#xff0c;傳統的方法是將特征圖與深度預測進行外積得到視椎特征圖&#xff0c;再將它與預處理好的體素索引結合&#xff0c;將每個視椎特征分類到每個voxel中進行累加和的操作。BEVFusion與BEVDepth等方法是避免了累加和&a…

藍橋杯常考的找規律題

目錄 靈感來源&#xff1a; B站視頻鏈接&#xff1a; 找規律題具有什么樣的特點&#xff1a; 報數游戲&#xff08;Java組&#xff09;&#xff1a; 題目描述&#xff1a; 題目鏈接&#xff1a; 思路詳解&#xff1a; 代碼詳解&#xff1a; 階乘求和&#xff08;Java組…

使用ffmpeg 將圖片合成為視頻,填充模糊背景,并添加兩段音樂

1.輸入3張圖片,每張播放一次,播放兩秒,視頻分辨率設置為1920:1080,每張圖片前0.3秒淡入,后0.3秒淡出,圖片寬高比不變,用白色填充空白區域 ffmpeg -loop 1 -t 2 -i "img1.jpg" \-loop 1 -t 2 -i "img2.jpg" \-loop 1 -t 2 -i "img3.jpg" \-filte…

PostgreSQL技術內幕29:事件觸發器tag原理解析

文章目錄 0.簡介1.概念說明2.tag的生成和存儲2.1 tag合法性校驗2.2 內存中存儲2.3 持久化存儲 3.tag的觸發 0.簡介 在上一篇文章中中&#xff0c;我們介紹了PG中的兩種觸發器&#xff0c;即適合于DML的普通觸發器和對于DDL的事件觸發器&#xff0c;其中事件觸發器與常規的 DML…

mysql 導入很慢,如何解決

精選 原創 碼出財富2025-04-14 17:35:14博主文章分類&#xff1a;數據庫©著作權 文章標簽mysql數據庫用戶名文章分類MySQL數據庫yyds干貨盤點閱讀數184 導入大型 SQL 文件到 MySQL 數據庫時&#xff0c;速度可能會受到影響。以下是一些優化方法和建議&#xff0c;幫助你…

多物理場耦合低溫等離子體裝置求解器PASSKEy2

文章目錄 PASSKEy2簡介PASSKEY2計算流程PASSKEy2 中求解的物理方程電路模型等離子體模型燃燒模型 PASSKEy2的使用 PASSKEy2簡介 PASSKEy2 是在 PASSKEy1 的基礎上重新編寫的等離子體數值模擬程序。 相較于 PASSKEy1&#xff0c; PASSKEy2 在具備解決低溫等離子體模擬問題的能力…

保姆級zabbix監控jmx、數據庫和網絡監控(SNMP)

前言 在當今數字化時代&#xff0c;企業IT基礎設施的穩定性與性能直接關系到業務連續性和用戶體驗。隨著系統復雜性的不斷增加&#xff0c;單一維度的監控已難以滿足全面運維需求。Zabbix作為一款功能強大的開源監控解決方案&#xff0c;通過整合JMX&#xff08;Java Manageme…

復雜地形越野機器人導航新突破!VERTIFORMER:數據高效多任務Transformer助力越野機器人移動導航

作者&#xff1a; Mohammad Nazeri 1 ^{1} 1, Anuj Pokhrel 1 ^{1} 1, Alexandyr Card 1 ^{1} 1, Aniket Datar 1 ^{1} 1, Garrett Warnell 2 , 3 ^{2,3} 2,3, Xuesu Xiao 1 ^{1} 1單位&#xff1a; 1 ^{1} 1喬治梅森大學計算機科學系&#xff0c; 2 ^{2} 2美國陸軍研究實驗室&…

SharpMap與TerraLib:C#與C++開源GIS庫

大家好&#xff0c;今天為大家介紹的軟件是SharpMap&#xff1a;一款專為了C#&#xff08;.NET&#xff09;環境設計的開源地圖和空間數據處理庫&#xff1b;TerraLib&#xff1a;一款由C編寫、支持多種數據庫的開源的GIS軟件庫。 下面&#xff0c;我們將從兩個開源軟件的主要…

音視頻學習 - MP3格式

環境 JDK 13 IDEA Build #IC-243.26053.27, built on March 16, 2025 Demo MP3Parser MP3 MP3全稱為MPEG Audio Layer 3&#xff0c;它是一種高效的計算機音頻編碼方案&#xff0c;它以較大的壓縮比將音頻文件轉換成較小的擴展名為.mp3的文件&#xff0c;基本保持源文件的音…

Unity中數據和資源加密(異或加密,AES加密,MD5加密)

在項目開發中&#xff0c;始終會涉及到的一個問題&#xff0c;就是信息安全&#xff0c;在調用接口&#xff0c;或者加載的資源&#xff0c;都會涉及安全問題&#xff0c;因此就出現了各種各樣的加密方式。 常見的也是目前用的最廣的加密方式&#xff0c;分別是&#xff1a;DE…

部署本地deepseek并在調用的詳細步驟以及解決一些可能出現的問題(Windows,Linux, WSL)

打開Ollama官網&#xff1a;https://ollama.com/ 直接下載Ollama并且安裝好Ollama、這時候就能看到app里多了個ollama&#xff0c;但是我們不用打開它 打開Windows Powershell&#xff1a; ollama run deepseek-r1:1.5b 7b 8b 14b 32b 70b 根據自己的電腦配置和需求更換不同的…

【KWDB 創作者計劃】_嵌入式硬件篇---寄存器與存儲器截斷與溢出

文章目錄 前言一、寄存器與存儲器1. 定義與基本概念寄存器(Register)位置功能特點存儲器(Memory)位置功能特點2. 關鍵區別3. 層級關系與協作存儲層次結構協作示例4. 為什么需要寄存器性能優化指令支持減少總線競爭5. 其他寄存器類型專用寄存器程序計數器(PC)棧指針(SP)…

小白自學python第二天

學習python的第二天 一、判斷語句 1、布爾類型和比較運算符 1、布爾類型 表示現實生活中的邏輯&#xff0c;真&#xff08;True&#xff0c;用數字1表示&#xff09;和假&#xff08;False&#xff0c;用數字0表示&#xff09; 2、布爾類型變量的定義 變量的名稱 布爾類…

linux基礎操作1------(文件命令)

一.前言 我們本章開始講解linux&#xff0c;我們對于linux得有重要的認識&#xff0c;比如項目部署等等&#xff0c;都會用到linux&#xff0c;今天我們就開始linux的學習&#xff0c;我們需要準備的工具有vmware和xshell&#xff0c;而這里我就不教大家虛擬機的安裝以及xshel…

編碼問題整合

一、windows系統編碼 查看編碼命令&#xff1a;chcp - 936 GBK - 65001 UTF-8 - 437 英文修改系統編碼 1、控制面板修改 需管理員權限-Windows 10/11進入 控制面板 > 區域 > 管理 > 更改系統區域設置勾選 Beta版: 使用Unicode UTF-8提供全球語言支持 → 重啟生效修…

如何配置Spark

1.上傳spark安裝包到某一臺機器&#xff08;自己在finaShell上的機器&#xff09;。 2.解壓。 把第一步上傳的安裝包解壓到/opt/module下&#xff08;也可以自己決定解壓到哪里&#xff09;。對應的命令是&#xff1a;tar -zxvf 安裝包 -C /opt/module 3.重命名。進入/opt/mo…

Redis 完整配置模板

一、基礎連接配置&#xff08;單機模式&#xff09; 基礎參數&#xff08;適用Spring Boot&#xff09; spring:redis:host: 127.0.0.1port: 6379password: your_passworddatabase: 0 # 默認DB索引timeout: 2000ms # 全局操作超時時間二、連接池參數&#xff08;通用核心配…

邊界凸臺建模與實例

文章目錄 邊界凸臺特征耳機案例瓶子 邊界凸臺特征 兩側對稱拉伸最上面的圓柱 同過兩點一基準面畫草圖&#xff0c;在基準面上畫橢圓 隱藏無關的實體和草圖&#xff0c;以便橢圓的端點能與線給穿透約束&#xff0c;下面的點與下面的線也給穿透&#xff0c;短軸長給35&#xff08…

河北省大數據應用創新大賽樣題

** 河北省大數據應用創新大賽樣題 ** 1. 在Linux下安裝Java并搭建完全分布式Hadoop集群。在Linux終端執行命令“initnetwork”&#xff0c;或雙擊桌面上名稱為“初始化網絡”的圖標&#xff0c;初始化實訓平臺網絡。 【數據獲取】 使用wget命令獲取JDK安裝包&#xff1a; “w…