Redis拓展之定時(shí)消息通知實(shí)現(xiàn)詳解
1. Redis實(shí)現(xiàn)定時(shí)消息通知
簡單定時(shí)任務(wù)通知: 利用redis的keyspace notifications(即:鍵過期后事件通知機(jī)制)
開啟方法
- 修改server.conf文件,找到notify-keyspace-events , 修改為“Ex”
- 使用cli命令:
redis-cli config set notify-keyspace-events Ex
- redis 配置參考
2. 例子
創(chuàng)建springboot項(xiàng)目
修改pom.xml 和 yml
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.9</version> <!-- 這個(gè)版本其實(shí)還是挺重要的,如果是2.7.3版本的話,大概會無法成功自動(dòng)裝載 RedisConnectionFactory --> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>cn.lazyfennec</groupId> <artifactId>redisdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>redisdemo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <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.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>
application.yml
spring: redis: database: 0 host: 192.168.1.7 port: 6379 jedis: pool: max-active: 8 max-idle: 8 min-idle: 0 max-wait: 1
創(chuàng)建RedisConfig
package cn.lazyfennec.redisdemo.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * @Author: Neco * @Description: * @Date: create in 2022/9/20 23:19 */ @Configuration @EnableCaching public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { // 設(shè)置序列化 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 配置redisTemplate RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); RedisSerializer stringSerializer = new StringRedisSerializer(); redisTemplate.setKeySerializer(stringSerializer); // key 序列化 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // value 序列化 redisTemplate.setHashKeySerializer(stringSerializer); // Hash key 序列化 redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); // Hash value 序列化 redisTemplate.afterPropertiesSet(); return redisTemplate; } }
創(chuàng)建RedisListenerConfiguration
package cn.lazyfennec.redisdemo.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.listener.RedisMessageListenerContainer; /** * @Author: Neco * @Description: * @Date: create in 2022/9/21 11:02 */ @Configuration public class RedisListenerConfiguration { @Autowired private RedisConnectionFactory factory; @Bean public RedisMessageListenerContainer redisMessageListenerContainer() { RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer(); redisMessageListenerContainer.setConnectionFactory(factory); return redisMessageListenerContainer; } }
事件監(jiān)聽事件 RedisTask
package cn.lazyfennec.redisdemo.task; import org.springframework.data.redis.connection.Message; import org.springframework.data.redis.listener.KeyExpirationEventMessageListener; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.stereotype.Component; import java.nio.charset.StandardCharsets; /** * @Author: Neco * @Description: * @Date: create in 2022/9/21 11:05 */ @Component public class RedisTask extends KeyExpirationEventMessageListener { public RedisTask(RedisMessageListenerContainer listenerContainer) { super(listenerContainer); } @Override public void onMessage(Message message, byte[] pattern) { // 接收到事件后回調(diào) String channel = new String(message.getChannel(), StandardCharsets.UTF_8); String key = new String(message.getBody(), StandardCharsets.UTF_8); System.out.println("key:" + key + ", channel:" + channel); } }
發(fā)布 RedisPublisher
package cn.lazyfennec.redisdemo.publisher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Random; import java.util.concurrent.TimeUnit; /** * @Author: Neco * @Description: * @Date: create in 2022/9/21 16:34 */ @Component public class RedisPublisher { @Autowired RedisTemplate<String, Object> redisTemplate; // 發(fā)布 public void publish(String key) { redisTemplate.opsForValue().set(key, new Random().nextInt(200), 10, TimeUnit.SECONDS); } // 循環(huán)指定時(shí)間觸發(fā) @Scheduled(cron = "0/15 * * * * ?") public void scheduledPublish() { System.out.println("scheduledPublish"); redisTemplate.opsForValue().set("str1", new Random().nextInt(200), 10, TimeUnit.SECONDS); } }
- 要實(shí)現(xiàn)Scheduled需要在啟動(dòng)類上加上注解
@SpringBootApplication @EnableScheduling // 要加上這個(gè),用以啟動(dòng) public class RedisdemoApplication {
修改TestController
package cn.lazyfennec.redisdemo.controller; import cn.lazyfennec.redisdemo.publisher.RedisPublisher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; /** * @Author: Neco * @Description: * @Date: create in 2022/9/21 16:32 */ @RestController public class TestController { @Autowired RedisPublisher redisPublisher; @GetMapping("/redis/{key}") public String publishEvent(@PathVariable String key) { // 發(fā)布事件 redisPublisher.publish(key); return "OK"; } }
以上就是Redis拓展之定時(shí)消息通知實(shí)現(xiàn)詳解的詳細(xì)內(nèi)容,更多關(guān)于Redis定時(shí)消息通知的資料請關(guān)注腳本之家其它相關(guān)文章!
- Redis定時(shí)監(jiān)控與數(shù)據(jù)處理的實(shí)踐指南
- Redis?延時(shí)任務(wù)實(shí)現(xiàn)及與定時(shí)任務(wù)區(qū)別詳解
- Spring boot詳解緩存redis實(shí)現(xiàn)定時(shí)過期方法
- Redis定時(shí)任務(wù)原理的實(shí)現(xiàn)
- Python定時(shí)從Mysql提取數(shù)據(jù)存入Redis的實(shí)現(xiàn)
- Spring Boot監(jiān)聽Redis Key失效事件實(shí)現(xiàn)定時(shí)任務(wù)的示例
- 基于redis實(shí)現(xiàn)定時(shí)任務(wù)的方法詳解
- Springboot使用Redis實(shí)現(xiàn)定時(shí)任務(wù)的三種方式
相關(guān)文章
redis中5種數(shù)據(jù)基礎(chǔ)查詢命令
本文主要介紹了redis中5種數(shù)據(jù)基礎(chǔ)查詢命令,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04Redis?緩存淘汰策略和事務(wù)實(shí)現(xiàn)樂觀鎖詳情
這篇文章主要介紹了Redis緩存淘汰策略和事務(wù)實(shí)現(xiàn)樂觀鎖詳情,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-07-07淺析PHP分布式中Redis實(shí)現(xiàn)Session的方法
這篇文章主要介紹了PHP分布式中Redis實(shí)現(xiàn)Session的方法,文中詳細(xì)介紹了兩種方法的使用方法,并給出了測試的示例代碼,有需要的朋友可以參考借鑒,下面來一起看看吧,2016-12-12Redis高并發(fā)緩存設(shè)計(jì)問題與性能優(yōu)化
本文詳細(xì)介紹了Redis緩存設(shè)計(jì)中常見的問題及解決方案,包括緩存穿透、緩存失效(擊穿)、緩存雪崩、熱點(diǎn)緩存key重建優(yōu)化、緩存與數(shù)據(jù)庫雙寫不一致以及開發(fā)規(guī)范與性能優(yōu)化,感興趣的可以了解一下2024-11-11redis緩存一致性延時(shí)雙刪代碼實(shí)現(xiàn)方式
這篇文章主要介紹了redis緩存一致性延時(shí)雙刪代碼實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08Redis的五種基本類型和業(yè)務(wù)場景和使用方式
Redis是一種高性能的鍵值存儲數(shù)據(jù)庫,支持多種數(shù)據(jù)結(jié)構(gòu)如字符串、列表、集合、哈希表和有序集合等,它提供豐富的API和持久化功能,適用于緩存、消息隊(duì)列、排行榜等多種場景,Redis能夠?qū)崿F(xiàn)高速讀寫操作,尤其適合需要快速響應(yīng)的應(yīng)用2024-10-10