商品秒杀
概述:
用zookeeper的节点来模拟商品数量用zookeeper锁的概念来解决线程安全问题,用Redis来解决数据访问慢,数据量大和刚并发的问题(这里数据如果特别多的话建议使用redis的分布式缓存)
@Controller
public class Fast{
// 商品数量,这里默认是zookeeper的节点来模拟商品
private static int number;
public static int getNumber() {
return number;
}
public static void setNumber(int number) {
MiaoSha.number = number;
}
public static ZooKeeper zooKeeper =null;
private static String PATH="/c";
public static void init() throws Exception{
//第二个参数代表连接超时的毫秒数
zooKeeper = new ZooKeeper("192.168.83.131:2181", 100000, new Watcher() {
//监听的方法 ,一旦有事件发生 ,该方法会自动调用
public void process(WatchedEvent watchedEvent) {
}
});
}
public static void process(){
//第二个参数watch 是监听的意思,一旦获取数据的路径的值发生变化 会执行一次监听事件
Stat stat = new Stat();
byte[] data = new byte[0];
try {
data = zooKeeper.getData(PATH, true, stat);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("获取到的数据:"+new String(data));
System.out.println("stat:"+stat);
}
@RequestMapping("/ave")
@ResponseBody
public DefaultMsg shangPin(Integer twe){
try {
MiaoSha.init();
MiaoSha.process();
//在每次去创建节点的时候就要先把节点全部删除掉
String path2 = "/c";
List<String> children2 = zooKeeper.getChildren("/c", false);
for (String path1 : children2) {
zooKeeper.delete(path2 + "/" + path1, -1);
}
//创建节点
int v=1;
for(int b=0;b<twe;b++) {
v++;
String create = zooKeeper.create(PATH+PATH+v, "c是一门编程语言".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
/* System.out.println(create);
System.out.println(PATH+"b"+v);*/
}
/*zooKeeper.setData("/c","100元话费优惠卷".getBytes(),-1);*/
List<String> children = zooKeeper.getChildren("/c", false);
System.out.println("获取所有的节点:");
int i = 0;
for (String path : children) {
i++;
System.out.println(path);
}
/*System.out.println(i);*/
number = i;
/*System.out.println(number);*/
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@RequestMapping("/simulation")
@ResponseBody
public Integer shang() throws Exception {
MiaoSha.init();
List<String> children = zooKeeper.getChildren("/c", false);
System.out.println("获取所有的节点:");
int i = 0;
for (String path : children) {
i++;
System.out.println(path);
}
return i;
}
}
具体的后续大家何以先私信我!这里我最近先不更新啦!