5秒执行一次定时任务---秒杀应用(在redis中初始化商品库存)
俩个重要的注解
@EnableScheduling 和@Scheduled
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import redis.clients.jedis.Jedis;
import java.util.List;
/**
- ClassName:RedisGoodsStoreInitTask
- Description:
- @date:2018/10/25 11:17
*/
@Configuration
@EnableScheduling
public class RedisGoodsStoreInitTask {
@Autowired
private GoodsService goodsService;
/**
* 5秒执行一次定时任务
* 在redis中初始化商品库存
*
*/
@Scheduled(cron="0/5 * * * * *")
public void initGoodsStore() {
//查询一下秒杀的商品
List<Goods> goodsList = goodsService.getAllGoods();
//jedis的获取(底层源码是通过jedispool.getResources()获得)
Jedis jedis = JedisPoolInstance.getJedisPoolInstance().getResource();
for (Goods goods : goodsList) {
//操作redis,将商品库存存入redis
jedis.setnx(CommonsConstants.SECKILL_STORE + goods.getRandomName(), String.valueOf(goods.getStore()));
}
jedis.close();
}
}
“********************************************************”
jedis缓存在项目中的应用
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
- redis连接池示例
- (单例模式)
*/
//自定义的类
public class JedisPoolInstance {
//redis服务器的ip地址
private static final String HOST = "192.168.136.128";
private static final String PASSWORD = "123456";
//redis服务器的端口
private static final int PORT = 6379;
//redis连接池对象
private static JedisPool jedisPool = null;
//私有构造方法
private JedisPoolInstance() {
}
/**
* 获取线程池实例对象
*
* @return
*/
public static JedisPool getJedisPoolInstance() {
if (null == jedisPool) {
synchronized (JedisPoolInstance.class) {
if (null == jedisPool) {
//对连接池的参数进行配置,根据项目的实际情况配置这些参数
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(1000);//最大连接数
poolConfig.setMaxIdle(32);//最大空闲连接数
poolConfig.setMaxWaitMillis(90*1000);//获取连接时的最大等待毫秒数
poolConfig.setTestOnBorrow(true);//在获取连接的时候检查连接有效性
jedisPool = new JedisPool(poolConfig, HOST, PORT, 15000, PASSWORD);
}
}
}
return jedisPool;
}
}
上一篇: 学习mockjs
下一篇: 关于Cast函数的文章推荐