訂單超時(shí)取消的實(shí)現(xiàn),首先想到的是定時(shí)任務(wù),但是這種實(shí)現(xiàn)方式在訂單量較大的情況下是有問(wèn)題的,而且時(shí)間也會(huì)有誤差,最大時(shí)間差就是定時(shí)任務(wù)的執(zhí)行間隔時(shí)間。
使用redis的過(guò)期監(jiān)聽(tīng)事件可以比較好的解決這個(gè)問(wèn)題。實(shí)現(xiàn)的方式是訂單創(chuàng)建后向redus中存一記錄,一般就以訂單號(hào)為key。設(shè)置過(guò)期時(shí)間(訂單超時(shí)時(shí)間),一旦時(shí)間超時(shí)會(huì)觸發(fā)監(jiān)聽(tīng)事件,這時(shí)候就可以通過(guò)key判斷這個(gè)訂單是否支付,未支付時(shí)取消訂單。
1.修改redis.windows.conf配置文件中notify-keyspace-events的值
默認(rèn)配置notify-keyspace-events的值為" ",修改為 notify-keyspace-events Ex 這樣便開(kāi)啟了過(guò)期事件
2. 創(chuàng)建配置類RedisListenerConfig(配置RedisMessageListenerContainer這個(gè)Bean)
@Configuration public class RedisListenerConfig { @Autowired private RedisTemplate redisTemplate; /** * 處理亂碼 * @return */ @Bean public RedisTemplate redisTemplateInit() { // key序列化 redisTemplate.setKeySerializer(new StringRedisSerializer()); //val實(shí)例化 redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); return container; } }
3.繼承KeyExpirationEventMessageListener創(chuàng)建redis過(guò)期事件的監(jiān)聽(tīng)類
KeyExpirationEventMessageListener類是org.springframework.data.redis.listener包下的實(shí)現(xiàn)類,通過(guò)繼承這個(gè)類重寫(xiě)onMessage方法可以實(shí)現(xiàn)對(duì)redis所有過(guò)期事件的監(jiān)聽(tīng)。
@Component public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener { public RedisKeyExpirationListener(RedisMessageListenerContainer container) { super(container); } /** * 針對(duì)redis數(shù)據(jù)失效事件,進(jìn)行數(shù)據(jù)處理 * @param message * @param pattern */ @Override public void onMessage(Message message, byte[] pattern) { String key=message.toString();//生效的key if (key!=null key.startsWith("order")){//從失效key中篩選代表訂單失效的key //截取訂單號(hào),查詢訂單,如果是未支付狀態(tài)則取消訂單 String orderNo=key.substring(5); System.out.println("訂單號(hào)為:"+orderNo+"的訂單超時(shí)未支付,取消訂單"); } } }
通過(guò)redis模擬創(chuàng)建一個(gè)有效時(shí)間為5s的訂單:
5秒后程序成功監(jiān)聽(tīng)到了過(guò)期事件:
到此這篇關(guān)于基于Redis過(guò)期事件實(shí)現(xiàn)訂單超時(shí)取消的文章就介紹到這了,更多相關(guān)Redis 訂單超時(shí)取消內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
標(biāo)簽:大慶 北京 江蘇 臺(tái)州 楊凌 吉安 朝陽(yáng) 果洛
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《基于Redis過(guò)期事件實(shí)現(xiàn)訂單超時(shí)取消》,本文關(guān)鍵詞 基于,Redis,過(guò)期,事件,實(shí)現(xiàn),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。