redis05 sprngboot整合redis

redis的Java客戶端

整合步驟

添加redis的pom依賴

<!-- 引入redis依賴 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency><!-- 引入redis連接池的依賴 -->
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId>
</dependency>

配置文件配置

spring:redis:database: 0host: 127.0.0.1port: 6379password:timeout: 5000lettuce:pool:max-active: 32max-wait: -1max-idle: 16min-idle: 8

編寫配置類

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** @author LH**/
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig {@Bean@ConditionalOnMissingBean(name = "redisTemplate")public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<Object, Object> template = new RedisTemplate<>();//使用fastjson序列化FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);// value值的序列化采用fastJsonRedisSerializertemplate.setValueSerializer(fastJsonRedisSerializer);template.setHashValueSerializer(fastJsonRedisSerializer);// key的序列化采用StringRedisSerializertemplate.setKeySerializer(new StringRedisSerializer());template.setHashKeySerializer(new StringRedisSerializer());template.setConnectionFactory(redisConnectionFactory);return template;}@Bean@ConditionalOnMissingBean(StringRedisTemplate.class)public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {StringRedisTemplate template = new StringRedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;}
}

編寫redis工具類RedisUtil.java

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;/*** Redis常用的一些操作** @author LH*/
@Component
public class RedisUtil {@Resourceprivate RedisTemplate<String, Object> redisTemplate;/*** 寫入緩存*/public boolean set(final String key, Object value) {boolean result = false;try {ValueOperations<String, Object> operations = redisTemplate.opsForValue();operations.set(key, value);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** 寫入緩存設置時效時間*/public boolean set(final String key, Object value, Long expireTime) {boolean result = false;try {ValueOperations<String, Object> operations = redisTemplate.opsForValue();operations.set(key, value);redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** 更新緩存*/public boolean getAndSet(final String key, String value) {boolean result = false;try {redisTemplate.opsForValue().getAndSet(key, value);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** 批量刪除對應的value*/public void remove(final String... keys) {for (String key : keys) {remove(key);}}/*** 批量刪除key*/public void removePattern(final String pattern) {Set<String> keys = redisTemplate.keys(pattern);if (CollectionUtils.isNotEmpty(keys)) {redisTemplate.delete(keys);}}/*** 刪除對應的value*/public void remove(final String key) {if (exists(key)) {redisTemplate.delete(key);}}/*** 判斷緩存中是否有對應的value*/public boolean exists(final String key) {Boolean isExists = redisTemplate.hasKey(key);return BooleanUtils.isTrue(isExists);}/*** 讀取緩存*/public Object get(final String key) {ValueOperations<String, Object> operations = redisTemplate.opsForValue();return operations.get(key);}/*** 哈希 添加*/public void hmSet(String key, Object hashKey, Object value) {HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();hash.put(key, hashKey, value);}/*** 哈希獲取數據*/public Object hmGet(String key, Object hashKey) {HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();return hash.get(key, hashKey);}/*** 列表添加*/public void lPush(String k, Object v) {ListOperations<String, Object> list = redisTemplate.opsForList();list.rightPush(k, v);}/*** 列表獲取*/public List<Object> lRange(String k, long l, long l1) {ListOperations<String, Object> list = redisTemplate.opsForList();return list.range(k, l, l1);}/*** 集合添加*/public void addSet(String key, Object value) {SetOperations<String, Object> set = redisTemplate.opsForSet();set.add(key, value);}/*** 刪除集合下的所有值*/public void removeSetAll(String key) {SetOperations<String, Object> set = redisTemplate.opsForSet();Set<Object> objectSet = set.members(key);if (objectSet != null && !objectSet.isEmpty()) {for (Object o : objectSet) {set.remove(key, o);}}}/*** 判斷set集合里面是否包含某個元素*/public Boolean isMember(String key, Object member) {SetOperations<String, Object> set = redisTemplate.opsForSet();return set.isMember(key, member);}/*** 集合獲取*/public Set<Object> setMembers(String key) {SetOperations<String, Object> set = redisTemplate.opsForSet();return set.members(key);}/*** 有序集合添加*/public void zAdd(String key, Object value, double source) {ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();zset.add(key, value, source);}/*** 有序集合獲取指定范圍的數據*/public Set<Object> rangeByScore(String key, double source, double source1) {ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();return zSet.rangeByScore(key, source, source1);}/*** 有序集合升序獲取*/public Set<Object> range(String key, Long source, Long source1) {ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();return zSet.range(key, source, source1);}/*** 有序集合降序獲取*/public Set<Object> reverseRange(String key, Long source, Long source1) {ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();return zSet.reverseRange(key, source, source1);}
}

redis Key過期處理事件

修改redis的配置文件

看一下notify-keyspace-events Ex是否被注釋(默認是注釋),放開注釋即可。

修改RedisConfig.java

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** @Description redis配置* @Author LH**/
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig
{@Bean@ConditionalOnMissingBean(name = "redisTemplate")public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){RedisTemplate<Object, Object> template = new RedisTemplate<>();//使用fastjson序列化FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);// value值的序列化采用fastJsonRedisSerializertemplate.setValueSerializer(fastJsonRedisSerializer);template.setHashValueSerializer(fastJsonRedisSerializer);// key的序列化采用StringRedisSerializertemplate.setKeySerializer(new StringRedisSerializer());template.setHashKeySerializer(new StringRedisSerializer());template.setConnectionFactory(redisConnectionFactory);return template;}@Bean@ConditionalOnMissingBean(StringRedisTemplate.class)public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory){StringRedisTemplate template = new StringRedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;}/*** 開啟監聽redis Key過期事件*/@Beanpublic RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory){RedisMessageListenerContainer container = new RedisMessageListenerContainer();container.setConnectionFactory(connectionFactory);return container;}
}

定義過期監聽器RedisKeyExpireListener

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;/*** @Description redis過期監聽器* @Author LH**/
@Slf4j
public class RedisKeyExpireListener extends KeyExpirationEventMessageListener
{public RedisKeyExpireListener(RedisMessageListenerContainer listenerContainer){super(listenerContainer);}@Overridepublic void onMessage(Message message, byte[] pattern){String expireKey = message.toString();// 根據過期的key處理對應的業務邏輯log.info(expireKey + "已過期-------------------");}
}

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

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

相關文章

51單片機學習day02

基于普中的stc89c52&#xff0c; 串口&#xff1a; 通訊接口&#xff0c;51單片機自帶UART&#xff08;通用異步收發器&#xff09;&#xff0c;可實現窗口通訊。 硬件電路&#xff1a; 簡單雙向串口通信有兩根通信線&#xff08;發送端TXD和接收端RXD&#xff09;&#xff0…

HelixToolKit的模型旋轉操作

前面加載了模型以后&#xff0c;鼠標拖動和縮放比較好操作&#xff1b;但是旋轉似乎沒有&#xff0c; 操作了一陣&#xff0c;也不是沒有&#xff0c;應該是還不熟悉&#xff1b; 旋轉的指示器在右下角&#xff0c;現在U面看到正面&#xff0c; 想看一下模型的背面&#xff0…

【Java項目介紹和界面搭建】拼圖小游戲——添加圖片

&#x1f36c; 博主介紹&#x1f468;?&#x1f393; 博主介紹&#xff1a;大家好&#xff0c;我是 hacker-routing &#xff0c;很高興認識大家~ ?主攻領域&#xff1a;【滲透領域】【應急響應】 【Java】 【VulnHub靶場復現】【面試分析】 &#x1f389;點贊?評論?收藏 …

扼殺網絡中的環路:STP、RSTP、MSTP

目錄 前言&#xff1a; 一、STP&#xff08;Spanning Tree Protocol&#xff09; 1.1 STP功能 1.2 STP應用 二、RSTP&#xff08;Rapid Spanning Tree Protocol&#xff09; 2.1 RSTP功能 2.2 RSTP應用 三、MSTP&#xff08;Multiple Spanning Tree Protocol&#xff0…

Angular 由一個bug說起之四:jsonEditor使用不當造成的bug

一&#xff1a;問題 項目中使用了一個JSON第三方庫&#xff1a; GitHub - josdejong/jsoneditor: A web-based tool to view, edit, format, and validate JSON 當用戶編輯JSON格式的數據&#xff0c;查找替換時&#xff1a; 用戶的期望結果是&#xff1a;$$ 被替換為$$_text&a…

[物聯網] OneNet 多協議TCP透傳

[物聯網] OneNet 多協議TCP透傳 STM32物聯網–ONENET云平臺的多協議接入產品創建 : https://blog.csdn.net/qq_44942724/article/details/134492924 Onenet tcp 透傳 : https://blog.csdn.net/flyme2010/article/details/107086001 tcp服務端測試工具 : http://tcp.xnkiot.com/…

zephyr學習

zephyr內核對象學習 定時器 類似linux的定時器&#xff0c; 可以分別設置第一次到期時間和后續的周期觸發時間&#xff0c; 可以注冊到期回調和停止回調 還有一個計數狀態&#xff0c;用于標記timer到期了多少次 duration&#xff1a;設定timer第一次到期的時間。 period: …

SpringBoot3.2.0整合MyBatis-plus的相關問題及處理方法

SpringBoot3.2.0整合MyBatis-plus的相關問題 文章目錄 SpringBoot3.2.0整合MyBatis-plus的相關問題1. build.gradle2. mybatis-plus整合問題1. 錯誤描述2. 問題分析及解決1. 原因分析2. 解決方式 Springboot3.2.0 GA版發布于 2023-11-24 環境&#xff1a;SpringBoot3.2.0Gradle…

【蛀牙】日常生活如何正確護理牙齒?刷牙、洗牙、補牙

程序員生活指南之 【蛀牙】日常生活如何正確護理牙齒&#xff1f;刷牙、洗牙、補牙 文章目錄 一、日常如何清洗牙齒&#xff1f;——刷牙與洗牙1、牙齒污垢1.1 牙菌斑1.2 軟垢1.3 牙結石1.4 牙齦出血 2、如何刷牙2.1 關于時間2.2 各種工具2.3 巴氏刷牙法 二、定期進行洗牙3、如…

題目 1076: 內部收益率

題目描述: 在金融中&#xff0c;我們有時會用內部收益率IRR來評價項目的投資財務效益&#xff0c;它等于使得投資凈現值NPV等于0的貼現率。換句話說&#xff0c;給定項目的期數T、初始現金流CF0和項目各期的現金流CF1, CF2, ...&#xff0c;CFT&#xff0c;IRR是下面方程的解&…

RISC-V特權架構 - 特權模式與指令

RV32/64 特權架構 - 特權模式與指令 1 特權模式2 特權指令2.1 mret&#xff08;從機器模式返回到先前的模式&#xff09;2.2 sret&#xff08;從監管模式返回到先前的模式&#xff09;2.3 wfi&#xff08;等待中斷&#xff09;2.4 sfence.vma&#xff08;內存屏障&#xff09; …

SpringBoot+Vue+MySQL:裝修管理新架構探索

??計算機畢業編程指導師 ??個人介紹&#xff1a;自己非常喜歡研究技術問題&#xff01;專業做Java、Python、微信小程序、安卓、大數據、爬蟲、Golang、大屏等實戰項目。 ??實戰項目&#xff1a;有源碼或者技術上的問題歡迎在評論區一起討論交流&#xff01; ?? Java、…

FPGA開源項目分享——2D N-Body重力模擬器

?導語 今天繼續康奈爾大學FPGA 課程ECE 5760的典型案例分享——2D N-Body重力模擬器。 &#xff08;更多其他案例請參考網站&#xff1a; Final Projects ECE 5760&#xff09; 1. 項目概述 項目網址 Grav Sim 項目說明 該項目的目標是創建一個用DE1-SOC進行硬件加速的2…

Java面試技巧

一、面試前準備 復習基礎知識&#xff1a;深入理解Java核心概念&#xff0c;如JVM、JDK、JRE等。熟悉Java基本語法、面向對象編程、異常處理、集合類、IO流等。同時&#xff0c;對Java的新特性&#xff0c;如Lambda表達式、Stream API等也要有所了解。強化算法和數據結構&…

簡易內存池2 - 華為OD統一考試(C卷)

OD統一考試&#xff08;C卷&#xff09; 分值&#xff1a; 200分 題解&#xff1a; Java / Python / C 題目描述 請實現一個簡易內存池,根據請求命令完成內存分配和釋放。 內存池支持兩種操作命令&#xff0c;REQUEST和RELEASE&#xff0c;其格式為: REQUEST請求的內存大小 …

Redis 【1】—— 安裝 與 配置

Redis 【1】—— 安裝 與 配置 一、安裝 與 配置&#xff08;一&#xff09;使用 yum 安裝&#xff08;二&#xff09;創建符號鏈接1. 軟鏈接2. 相關指令 &#xff08;三&#xff09;修改配置文件&#xff08;四&#xff09;Redis 的啟停 一、安裝 與 配置 &#xff08;一&…

Java的強引用、軟引用、弱引用和虛引用詳解。

Java的強引用、軟引用、弱引用和虛引用 1. 強引用2. 軟引用3. 弱引用4. 虛引用 總結 Java的強引用、軟引用、弱引用和虛引用可以用來標識GC時判斷對象是否達到回收的條件&#xff0c;下面結合Java代碼看看這四類引用吧。 1. 強引用 是最普通的引用方式&#xff0c;通過new關鍵…

外貿業務員沒客戶的7大原因+解決辦法!

業務員沒有客戶&#xff0c;就是無源之水&#xff0c;無本之木&#xff0c;這自然也就沒有業績。那些吃空餉的業務員&#xff0c;遲早會拖垮公司。所以不管是什么原因導致的業務員沒客戶&#xff0c;都要一一查驗清楚。七個業務員沒有客戶的原因&#xff0c;七種對策&#xff0…

華為數通方向HCIP-DataCom H12-821題庫(多選題:21-40)

第21題 管理員在配置 VRRP 時,下面哪些不是必須配置的? A.搶占模式 B.搶占延時 C.虛擬IP 地址 D.虛擬路由器的優先級 【參考答案】ABD 【答案解析】 VRRP的作用之一是提供一個虛擬的IP地址,用作默認網關,用來實現冗余和故障轉移。因此,配置虛擬IP地址是必須的。華為設備vr…

hcip交換

交換機功能 無限的傳輸距離——識別&#xff0c;重寫電信號&#xff08;幀&#xff09;保證信息完整徹底解決了沖突二層單播——MAC地址表提高端口密度 單播地址&#xff1a;MAC地址第一個字節第8位為0 組播地址&#xff1a;MAC地址第一個字節第8位為1 廣播地址&#xff1a;全1…