导入pom依赖
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置文件
spring:
redis:
port: 6379
host: 127.0.0.1
database: 0
password:
jedis:
pool:
max-active: 8
max-wait: -1ms
max-idle: 8
min-idle: 0
timeout: 5000ms
Config配置
package com.iwuyu.config;
import lombok.extern.slf4j.Slf4j;
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;
@Slf4j
@Configuration
public class RedisListenerConfig {
@Bean
public RedisMessageListenerContainer container(RedisConnectionFactory redisConnectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(redisConnectionFactory);
log.info("redis监听配置生效");
return container;
}
}
监听Redis过期
package com.iwuyu.config;
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 lenovo
*/
@Component
public class KeyExpiredListener extends KeyExpirationEventMessageListener {
public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
@Override
public void onMessage(Message message, byte[] pattern) {
String channel = new String(message.getChannel(), StandardCharsets.UTF_8);
String key = new String(message.getBody(), StandardCharsets.UTF_8);
System.out.println("redis key 过期:pattern={"+new String(pattern)+"},channel={"+channel+"},key={"+key+"}");
}
}
写接口存入Redis信息
@GetMapping
public String addRedis(){
redisTemplate.opsForValue().set("email", "这是我的邮箱", 30, TimeUnit.SECONDS);
return "key:email,value:这是我的邮箱";
}
测试
浏览器调用该接口。
redis存储信息
redis过期后台自动执行
应用场景
订单的自动取消支付、自动收货等。