redis秒殺

13746 ワード

package com.test.springdemo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

@RestController
public class OrderController {

    @Autowired
    private StringRedisTemplate redisTemplate;


    @GetMapping(value = "purchase/{productId}")
    public boolean purchase(@PathVariable("productId") String productId) {
    /*    redisTemplate.opsForZSet().add("zset","1",0.1);
        redisTemplate.opsForZSet().add("zset","2",0.2);
        Set> zet = redisTemplate.opsForZSet().rangeWithScores("zset1", 0, -1);
        Iterator> iterator = zet.iterator();
        while (iterator.hasNext()){
            ZSetOperations.TypedTuple next = iterator.next();
            System.out.println(next.getValue());
        }*/
        if (productId==null) return false;

        long orderNum = System.currentTimeMillis();

        //              
        boolean temp = redisTemplate.opsForSet().isMember("orderNum",orderNum+"");
        if (temp) return true;

        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.watch("product:"+productId);

        String productNum = redisTemplate.opsForValue().get("product:"+productId);
        if(null==productNum ) {return false;}
        long num = Long.valueOf(productNum );
        //         
        if (num<=0){
            //         
            redisTemplate.opsForList().leftPush("state","   ="+orderNum+"----    ="+productId+"----     ");
            return false;
        }
        redisTemplate.multi();//  
        redisTemplate.boundValueOps("product:"+productId).decrement(1);
        redisTemplate.opsForSet().add("orderNumber",orderNum+"");
        List<Object> exec = redisTemplate.exec();
        if (exec==null||exec.size()==0){
            redisTemplate.opsForList().rightPush("state","   ="+orderNum+"----    ="+productId+"----    ");
            return false;
        }else{
            redisTemplate.opsForList().rightPush("state","   ="+orderNum+"----    ="+productId+"----    ");
            return true;//      
        }
    }

}