Spring定时任务Scheduled

把秒杀商品通过定时任务存到Redis

applicationContext-task.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:p="http://www.springframework.org/schema/p"
      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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/task
       http://www.springframework.org/schema/task/spring-task.xsd">

   <!--包扫描-->
   <context:component-scan base-package="fun.chennqi.seckill.task"/>
   <!--开启注解驱动-->
   <task:annotation-driven/>
</beans>
java
@Component
public class SeckillGoodsTask {
   @Autowired
   private TbSeckillGoodsMapper seckillGoodsMapper;
   @Autowired
   private RedisTemplate redisTemplate;

   //    把mysql中需要秒杀的商品放入到redis中
   @Scheduled(cron = "59 14 19 14 12 ?")
   public void initSeckillGoods() {
       // 1、查询符合要求的数据
       // 要求:审核通过+时间范围之内+库存大于0
       // select * from tb_seckill_goods where STATUS='1' and stock_count>0
       // and  start_time<now() and  end_time>now()
       TbSeckillGoodsExample example = new TbSeckillGoodsExample();
       example.createCriteria()
               .andStatusEqualTo("1")
               .andStockCountGreaterThan(0)
               .andStartTimeLessThan(new Date())
               .andEndTimeGreaterThan(new Date());
       List<TbSeckillGoods> tbSeckillGoods = seckillGoodsMapper.selectByExample(example);
       // 2、把数据一个一个地放到redis中
       for (TbSeckillGoods tbSeckillGood : tbSeckillGoods) {
           redisTemplate.boundHashOps("seckill_goods").put(tbSeckillGood.getId(), tbSeckillGood);
           for (int i = 0; i < tbSeckillGood.getStockCount(); i++) {
               // 把商品的id放入到Redis队列中
               redisTemplate.boundListOps("seckill_goods_" + tbSeckillGood.getId()).rightPush(tbSeckillGood.getId());
           }
       }
       System.out.println("商品已放入到redis中");
   }
}
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        id="WebApp_ID" version="3.0">
 <display-name>pyg-task-service</display-name>
 <!--配置Spring监听-->
 <context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath*:spring/*.xml</param-value>
 </context-param>
 <listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <welcome-file-list>
   <welcome-file>index.html</welcome-file>
 </welcome-file-list>
</web-app>

1

发表评论