在下完单后,如果15分钟内没有成功支付,那么就应该自动取消订单,因为Redis是可以支持设置过期时间的,并且还支持监听key过期,这个时候我们使用监听key过期的方式即可完成我们的自动取消订单功能。
一、准备操作
先检查Redis的配置文件notify-keyspace-events Ex 是不是被注释了,如果被注释了则要取消
1、建立订单表
create table order_form(
id int primary key auto_increment,
state int comment'订单状态(1:待付款,2:已付款,3:已关闭)'
);
注:这里我们只需要最重要的两个字段即可,其他的请自己加上。
2、编写实体类
3、编写Dao层
4、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
接下来开始正式操作
二、在RedisConf类增加代码
@Bean
RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
return container;
}
三、编写RedisKeyExpirationListener类
import lombok.extern.slf4j.Slf4j;
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 org.springframework.util.Assert;
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
@Autowired
private OrderFormDao orderFormDao;
public RedisKeyExpirationListener(RedisMessageListenerContainer redisMessageListenerContainer) {
super(redisMessageListenerContainer);
}
@Override
public void onMessage(Message message, byte[] pattern) {
String keyName=message.toString();
log.info("key名{}",keyName);
if(keyName.contains("orderTimeOut")){
int orderId=Integer.parseInt(keyName.replaceAll("orderTimeOut",""));
OrderForm orderForm=orderFormDao.selectById(orderId);
Assert.notNull(orderForm,"订单不存在");
if(orderForm.getState()==1){
orderFormDao.updateById(new OrderForm()
.setState(3)
.setId(orderId)
);
}else{
log.info("订单id{}状态已改变",orderId);
}
}
}
}
四、编写测试类
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.TimeUnit;
@SpringBootTest
public class GenerateUserShowIdTest {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private OrderFormDao orderFormDao;
@Test
public void test(){
OrderForm orderForm=new OrderForm()
.setState(1);
orderFormDao.insert(orderForm);
int id=orderForm.getId();
redisTemplate.opsForValue().set("orderTimeOut"+id,id,15, TimeUnit.MINUTES);
}
}
至此已经完成了监听key过期并实现自动取消订单
注意事项
- 监听key过期时,只能获取到失效的key名,不能获取到值,需要把值拼接到key的后面才行,然后通过截取或替换的方式来拿到值。
- 监听key过期类,需要判断key是否包含orderTimeOut,包含才能走取消订单的流程。
遇到的问题
- 不在RedisConf类加上如下代码
RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
return container;
}
启动项目时则会报
Parameter 0 of constructor in com.h.a.c.config.RedisKeyExpirationListener required a bean of type 'org.springframework.data.redis.listener.RedisMessageListenerContainer' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.data.redis.listener.RedisMessageListenerContainer' in your configuration.
缺点
- 如果监听到了key,然后执行取消订单的业务,如果业务执行时报错了,那么该订单将永远无法自动取消。
- 如果项目突然宕机了,然后某个key又是在宕机的时候过期,那么该key对应的订单将无法自动取消。
下面我们就来讲一下如何解决这两个问题
建立取消订单表
create table order_time(
id int primary key auto_increment,
order_id int comment'订单id',
timeout_time datetime comment'超时时间',
create_time TIMESTAMP comment'创建时间'
);
然后编写对应的实体类和dao层,这里我就不写了。
在下订单时插入数据
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
@SpringBootTest
public class TestRedis {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private OrderFormDao orderFormDao;
@Autowired
private OrderTimeDao orderTimeDao;
@Test
@Transactional(rollbackFor = Exception.class)
@Rollback(value = false)
public void test() throws ParseException {
OrderForm orderForm=new OrderForm()
.setState(1);
orderFormDao.insert(orderForm);
int id=orderForm.getId();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
OrderTime orderTime=new OrderTime()
.setOrderId(id)
.setTimeoutTime(sdf.parse("2022-02-02 12:12:11"));
orderTimeDao.insert(orderTime);
redisTemplate.opsForValue().set("orderTimeOut"+id,id,15, TimeUnit.MINUTES);
}
}
注:单元测试加上@Transactional是不会修改数据库的数据的,需要配合@Rollback一起使用。
取消订单时的操作
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
@Autowired
private OrderFormDao orderFormDao;
@Autowired
private OrderTimeDao orderTimeDao;
public RedisKeyExpirationListener(RedisMessageListenerContainer redisMessageListenerContainer) {
super(redisMessageListenerContainer);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void onMessage(Message message, byte[] pattern) {
String keyName=message.toString();
log.info("key名{}",keyName);
if(keyName.contains("orderTimeOut")){
int orderId=Integer.parseInt(keyName.replaceAll("orderTimeOut",""));
OrderForm orderForm=orderFormDao.selectById(orderId);
Assert.notNull(orderForm,"订单不存在");
if(orderForm.getState()==1){
try {
orderFormDao.updateById(new OrderForm()
.setState(3)
.setId(orderId));
orderTimeDao.delete(new QueryWrapper<OrderTime>().eq("order_id",orderId));
}catch (Exception e){
}
}else{
log.info("订单id{}状态已改变",orderId);
}
}
}
}
注:支付成功也需要删掉orderTime对应的数据
编写宕机补偿类
如果项目宕机了,恰好这时候Redis的key刚好过期,那么该订单将永远无法自动取消,编写宕机补偿类就是为了解决这个问题。
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.List;
@Component
public class OrderTimeOut {
@Autowired
private OrderTimeDao orderTimeDao;
@Autowired
private OrderFormDao orderFormDao;
@PostConstruct
@Transactional(rollbackFor = Exception.class)
public void init(){
List<OrderTime> list=orderTimeDao.selectList(new QueryWrapper<>());
OrderForm orderForm=null;
for (OrderTime orderTime : list) {
orderForm=orderFormDao.selectById(orderTime.getId());
if(orderForm!=null&&orderForm.getState()==1){
orderFormDao.updateById(new OrderForm()
.setState(3)
.setId(orderTime.getId()));
orderTimeDao.delete(new QueryWrapper<OrderTime>().eq("order_id",orderTime.getId()));
}
}
}
}
至此,所有问题均已解决,接下来我会继续总结集群监听key过期。
|