应用场景,优惠卷过期,监听
配置类文章来源:https://www.toymoban.com/news/detail-633852.html
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.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory redisConnectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(redisConnectionFactory);
return container;
}
}
监听类文章来源地址https://www.toymoban.com/news/detail-633852.html
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class RedisListenerComponent extends KeyExpirationEventMessageListener {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private final String SET_NX = "setnx:";
public RedisListenerComponent(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
@Override
public void onMessage(Message message, byte[] pattern) {
super.onMessage(message, pattern);
String expiredKey = message.toString();
//判定key的前缀,避免消费到自己
if (!expiredKey.startsWith(SET_NX)){
// 加锁操作,避免重复消费
Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(SET_NX + expiredKey, String.valueOf(System.currentTimeMillis()),30, TimeUnit.SECONDS);
if (flag){
System.out.println(expiredKey);
stringRedisTemplate.delete(SET_NX + expiredKey);
System.out.println("删除锁...");
}
}
}
}
到了这里,关于Redis,过期监听的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!