1、把秒杀的商品添加到redis
Goods g
= new Goods();
g
.setGoodsName("某某笔记本电脑");
g
.setPrice(new BigDecimal(9500.00));
g
.setStock(50);
g
.setId(2);
redisTemplate
.boundHashOps(Goods
.class.getSimpleName()).put(g
.getId(),g
);
for (int i
=0;i
<g
.getStockCount
;i
++){
redisTemplate
.boundListOps(TbPubliclecture
.class.getName()+"_"+id
).leftPush(id
);
}
2、编写业务逻辑
public String
saveOrder(Integer id
, String userId
) {
Boolean resoult
= redisTemplate
.boundSetOps(Constant
.CONSTANT_USERID_PRBFIX
+id
).isMember(userId
);
if (resoult
){
return "您已经请购过了,本次秒杀限购一次";
}
id
= (Integer
) redisTemplate
.boundListOps(Constant
.CONSTANT_SECKILLGOODS_ID_PRBFIX
+id
).rightPop();
if (null
==id
){
return "商品已售空,请选择其他商品";
}
redisTemplate
.boundSetOps(Constant
.CONSTANT_USERID_PRBFIX
+id
).add(userId
);
OrderRecord orderRecord
= new OrderRecord(id
,userId
);
redisTemplate
.boundListOps(OrderRecord
.class.getSimpleName()).leftPush(orderRecord
);
asyncService
.executeAsync();
return "秒杀成功";
}
创建一个对象用来储存商品的id和用户的id
@Data
public class OrderRecord implements Serializable {
private Integer id
;
private String userId
;
}
3、编写一个线程池
@Configuration
@EnableAsync
public class ExecutorConfig {
private static final Logger logger
= LoggerFactory
.getLogger(ExecutorConfig
.class);
@Bean
public Executor
asyncServiceExecutor() {
logger
.info("start asyncServiceExecutor");
ThreadPoolTaskExecutor executor
= new ThreadPoolTaskExecutor();
Integer pollNum
= Runtime
.getRuntime().availableProcessors();
executor
.setCorePoolSize(6);
executor
.setMaxPoolSize(50);
executor
.setKeepAliveSeconds(300);
executor
.setQueueCapacity(10000);
executor
.setThreadNamePrefix("async-service-");
executor
.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor
.initialize();
return executor
;
}
}
4、秒杀成功,异步处理数据
@Service
public class AsyncServiceImpl implements AsyncService {
@Autowired
private RedisTemplate redisTemplate
;
@Autowired
private RedisSetNxLock redisLock
;
private String lockKey
= "lockKey ";
@Override
@Async("asyncServiceExecutor")
public void executeAsync() {
try {
OrderRecord orderRecord
= (OrderRecord
) redisTemplate
.boundListOps(OrderRecord
.class.getSimpleName()).rightPop();
if (null
!= orderRecord
){
System
.out
.println("商品id::"+orderRecord
.getId());
Goods gg
= (Goods
) redisTemplate
.boundHashOps(Goods
.class.getSimpleName()).get(orderRecord
.getId());
System
.out
.println("库存::"+gg
.toString());
synchronized (AsyncServiceImpl
.class){
gg
= (Goods
) redisTemplate
.boundHashOps(Goods
.class.getSimpleName()).get(orderRecord
.getId());
gg
.setStock(gg
.getStock()-1);
System
.out
.println("商品剩余库存"+gg
.getStock());
if (gg
.getStock()<=0){
redisTemplate
.boundHashOps(Goods
.class.getSimpleName()).delete(orderRecord
.getId());
}else{
redisTemplate
.boundHashOps(Goods
.class.getSimpleName()).put(orderRecord
.getId(),gg
);
}
}
}
} catch (Exception e
) {
e
.printStackTrace();
}
}
}
快去使用Jmeter压测试试把