首页 > 数据库 >springboot~redis的hash结构为key设置过期策略

springboot~redis的hash结构为key设置过期策略

时间:2024-04-28 10:45:11浏览次数:30  
标签:__ hash springboot events set4 key public redisTemplate KeyExpiredEventMessageLi

redis配置文件开启键过期

#  The "notify-keyspace-events" takes as argument a string that is composed
#  of zero or multiple characters. The empty string means that notifications
#  are disabled.
#
#  Example: to enable list and generic events, from the point of view of the
#           event name, use:
#
#  notify-keyspace-events Elg
#
#  Example 2: to get the stream of the expired keys subscribing to channel
#             name __keyevent@0__:expired use:
#
#  notify-keyspace-events Ex
#
#  By default all notifications are disabled because most users don't need
#  this feature and the feature has some overhead. Note that if you don't
#  specify at least one of K or E, no events will be delivered.

springboot中实现键后的处理逻辑

  • 订阅逻辑
public class KeyExpiredEventMessageListener implements MessageListener {

	private final RedisTemplate redisTemplate;

	public KeyExpiredEventMessageListener(RedisTemplate redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	@Override
	public void onMessage(Message message, byte[] pattern) {
		String expiredKey = message.toString();
		// 处理键过期事件逻辑
		System.out.println("Key expired: " + expiredKey);
		String[] keys = expiredKey.split("\\:");
		redisTemplate.opsForHash().delete(keys[0], keys[1]);
	}

}
  • 注册组件
	@Bean
	public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory,
																	   KeyExpiredEventMessageListener keyExpiredEventMessageListener) {
		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(connectionFactory);
		container.addMessageListener(keyExpiredEventMessageListener, new PatternTopic("__keyevent@*__:expired"));//__keyevent@0__:expired  #0代表redis中的db索引
		return container;
	}

	@Bean
	public KeyExpiredEventMessageListener keyExpiredEventMessageListener(RedisTemplate redisTemplate) {
		return new KeyExpiredEventMessageListener(redisTemplate);
	}
  • 测试demo
@Test
public void hashsetExpire4() throws InterruptedException {
	redisTemplate.opsForHash().put("h_set4", "a", "1");
	redisTemplate.opsForHash().put("h_set4", "b", "2");
	redisTemplate.opsForValue().set("h_set4:b", "2");
	redisTemplate.expire("h_set4:b", Duration.ofSeconds(10));// 多次设置时,以最后一次为准,这时有效期重设为1分
	Thread.sleep(1000 * 60);

}

测试用例中,在10秒后,由于h_set4:b这个键过期了,所以触发了KeyExpiredEventMessageListener事件,最后将对应的hashset里的键被动删除。

标签:__,hash,springboot,events,set4,key,public,redisTemplate,KeyExpiredEventMessageLi
From: https://www.cnblogs.com/lori/p/18163255

相关文章

  • SpringBoot中几种好用的代码生成器(基于Mybatis-plus生成entity、mapper、xml等)
    前言熟悉Spring框架的同学一定都知道MVC开发模式吧,控制器(Controller)、业务类(Service)、持久层(Repository)、数据库映射(Mapper)、各种DO类构成了我们服务端的代码。初学的时候,觉得新鲜手写这些东西不觉得有啥,但是写久了就会觉得很烦。好不容易在数据库中写完了一遍字段,在Java代码又要......
  • SpringBoot常用注解(部分)
     @Service:注解在类上,表示这是一个业务层bean@Controller:注解在类上,表示这是一个控制层bean@Repository:注解在类上,表示这是一个数据访问层bean@Component:注解在类上,表示通用bean,value不写默认就是类名首字母小写@Autowired:按照类型(Spring容器默认单例模......
  • SpringBoot集成minio前后端联调
    基本配置初始化项目新建一个SpringBoot项目,集成lombokmybatis-plusminiohutool-core(可有可无)。新建一个数据表attachement,用于存储文件上传后在minio中的位置。droptableifexistsattachment;createtableattachment(idintauto_increment......
  • 一个通用的SpringBoot项目响应实体类Response
    packagecom.luky.vo;importlombok.AllArgsConstructor;importlombok.Data;importlombok.NoArgsConstructor;importlombok.ToString;importorg.springframework.http.HttpStatus;@Data@ToString@AllArgsConstructor@NoArgsConstructorpublicclassResponse&......
  • SpringBoot+MyBatisPlus报错 Invalid value type for attribute 'factoryBeanObjectTy
    依赖版本org.springframework.boot:spring-boot-starter-web:3.2.5com.baomidou:mybatis-plus-boot-starter:3.5.5错误Invalidvaluetypeforattribute'factoryBeanObjectType'问题原因:这个问题是由于依赖传递导致,在MyBatis起步依赖中的myBatis-spring版本过低,导致程......
  • springboot链接redis IPV6
    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><exclusions><exclusion>......
  • keycloak~RequiredActionProvider中获取表单认证前URL的参数
    在keycloak中,我们在进行brower浏览器的表单认证时,一般在跳到本页面时,URL上会有redirect_uri这种参数,用来告诉keycloak,在认证成功后的跳转地址,你在表单认证控制器中,可以通过context.getHttpRequest().getUri().getQueryParameters().getFirst("redirect_uri")进行获取,而当你为browe......
  • springBoot源码(一)
    构造函数运行代码publicConfigurableApplicationContextrun(String...args){ Startupstartup=Startup.create(); if(this.registerShutdownHook){ SpringApplication.shutdownHook.enableShutdownHookAddition(); } DefaultBootstrapContextbootstrapConte......
  • SpringBoot整合AOP实现打印方法执行时间切面
    pom.xml<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>代码创建注解importjava.lang.annotation.ElementType;importja......
  • IDEA中springboot项目编译两次的问题
    原因:因为在导入项目的之后,项目无法运行,问题1:显示缺少org.springbootframe的依赖,不知道怎么解决,网上搜了个方法,就是勾选下图的选项,意思是把build操作由IDEA交给Maven,勾选之后确实可以启动项目了但是后面在执行Mybatis时,问题2:我发现无论如何都会报一个唯一键值重复的错误,思考原因......