工作上需要做一个秒杀系统,在web端将秒杀信息插入redis中缓存起来,后台使用跑批任务将redis中的数据依次插入mysql中。由web端和redis来控制秒杀数量,后台只实现插入mysql库中。
不知道这个方法是否适合做秒杀系统,写出来希望大家来指点一下。
代码片段
Spring版本:4.3.6.RELEASE
- Spring.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<context:component-scan base-package="indi.smt.receiver"/>
<context:annotation-config />
<task:annotation-driven scheduler="myScheduler" executor="myExecutor"/>
<task:executor id="myExecutor" pool-size="5" />
<task:scheduler id="myScheduler" pool-size="10" />
<task:scheduled-tasks>
<task:scheduled ref="jobComponent" method="doJob" cron="11/3 * * * * ?"/>
</task:scheduled-tasks>
</beans>
- Job类
package indi.smt.receiver.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @author 無痕剑
* @date 2017/3/7 14:31
*/
@Component("jobComponent")
public class Job {
@Scheduled(cron = "/3 * * * * *")
public void doJob(){
System.out.println("执行。。。。");
}
}
- AppTest类
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author 無痕剑
* @date 2017/3/7 16:46
*/
public class AppTest {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:/spring-*.xml");
for (int i = 1;;i++) {
System.out.println("正在循环"+i+"。。。");
try {
Thread.sleep(10000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
这里需要注意的问题:
最关键的一点,导致我的程序一直报错,是由于
cron = "*/5 * * * * *"
这个cron表达式,有关cron表达式可以参考网上其他博客,非常详细,在使用在线cron表达式解析的时候,参考该条非常有必要。在这里,表示每5秒执行一次,必须是“*/5”,不能只写”/5”,否则会报错:java.lang.IllegalStateException: Encountered invalid @Scheduled method 'doJob': For input string: ""
spring.xml中,为
<task:annotation-driven/>
标签配置以下两个标签是为了多线程使用,如果只使用单线程,可以不写以下两个标签:<task:executor/> 和 <task:scheduler/>
。- 使用
<task:scheduled-tasks>
标签和Job.doJob()方法上配置注解@Scheduled(cron = "/5 * * * * *")
只需要使用一个就可以了,这里我更喜欢注解模式。 - 启动项目实际上只需要一句
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:/spring-*.xml");
就会自己执行了。 - 在spring.xml中配置