springboot 集成redis做一个简单的秒杀系统

项目是有地址的,我会放到文章的最后面

1. 直接service,我们会介绍两种秒杀模式

public interface GoodsService {

    /**
     * 通过lua脚本实现的秒杀
     * @param skuCode 商品编码
     * @param buyNum 购买数量
     * @return 购买数量
     */
    Long flashSellByLuaScript(String skuCode,int buyNum);
    /**
     * 通过redis 事务 实现的秒杀
     * @param skuCode 商品编码
     * @param buyNum 购买数量
     * @return 购买数量
     */
    Long flashSellByRedisWatch(String skuCode,int buyNum);





}

2. service实现类

 

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Long flashSellByLuaScript(String skuCode,int num) {
    	//下面是lua脚本
        String luaScript ="local buyNum = ARGV[1]\n" +
                "local goodsKey = KEYS[1]  \n" +
                "local goodsNum = redis.call('get',goodsKey) \n" +
                "if goodsNum >= buyNum \n" +
                "then redis.call('decrby',goodsKey,buyNum) \n" +
                "return buyNum \n" +
                "else \n" +
                "return '0'\n" +
                "end\n" +
                "\n" ;

        DefaultRedisScript<String> re = new DefaultRedisScript<String>();
        //设置脚本
        re.setScriptText(luaScript);
        //定义返回值类型,注意,如果没有这个定义,Spring不会返回结果
        re.setResultType(String.class);
        RedisSerializer<String> stringRedisSerializer = stringRedisTemplate.getStringSerializer();
        //执行LUA脚本
        String result = (String) stringRedisTemplate.execute(re, stringRedisSerializer, stringRedisSerializer, null);
        return Long.valueOf(result);
    }

    @Override
    public Long flashSellByRedisWatch(String skuCode,int num){

        SessionCallback<Long> sessionCallback = new SessionCallback<Long>() {
            @Override
            public Long execute(RedisOperations operations) throws DataAccessException {
                int result = num;
                //redis 乐观锁
                //我们观察商品编码是否发生改变
                operations.watch(skuCode);
                ValueOperations<String, String> valueOperations = operations.opsForValue();
                String goodsNumStr = valueOperations.get(skuCode);
                Integer goodsNum = Integer.valueOf(goodsNumStr);
                //标记一个事务块的开始。
                //事务块内的多条命令会按照先后顺序被放进一个队列当中,
                //最后由 EXEC 命令原子性(atomic)地执行。
                operations.multi();
                if (goodsNum >= num) {
                    valueOperations.increment(skuCode, 0 - num);
                } else {
                    result = 0;
                }
                //多条命令执行的结果集合
                List exec = operations.exec();
                if(exec.size()>0){
                    System.out.println(exec);
                }
                return (long) result;
            }
        };
        return stringRedisTemplate.execute(sessionCallback);
    }
//省略 其他的方法


}

3. controller
但是首先要向你的redis里面仍一个数据,key='xiaomi',value='100'


    @ApiOperation(value = "用事务秒杀测试接口", notes = "用事务秒杀测试接口")
    @RequestMapping(value = "/miaoTransaction", method = RequestMethod.GET)
    @ResponseBody
    public Long miaoTransaction() {

        Long res = goodsService.flashSellByRedisWatch("xiaomi", 1);
        return res;
    }


    @ApiOperation(value = " 秒杀Lua测试接口", notes = "秒杀Lua测试接口")
    @RequestMapping(value = "/miaoLua", method = RequestMethod.GET)
    @ResponseBody
    public Long miaoLua() {

        Long res = goodsService.flashSellByRedisWatch("xiaomi", 1);
        System.out.println(res.toString());
        return res;
    }

然后就可以用jemeter并发访问了

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
spring-boot-seckill分布式秒杀系统一个SpringBoot开发的从0到1构建的分布式秒杀系统,项目案例基本成型,逐步完善中。 开发环境: JDK1.8、Maven、Mysql、IntelliJ IDEA、SpringBoot1.5.10、zookeeper3.4.6、kafka_2.11、redis-2.8.4、curator-2.10.0 启动说明: 1、启动前 请配置application.properties中相关redis、zk以及kafka相关地址,建议在Linux下安装使用。 2、数据库脚本位于 src/main/resource/sql 下面,启动前请自行导入。 3、配置完成,运行Application中的main方法,访问 http://localhost:8080/seckill/swagger-ui.html 进行API测试。 4、秒杀商品页:http://localhost:8080/seckill/index.shtml ,部分功能待完成。 5、本测试案例单纯为了学习,某些案例并不适用于生产环境,大家根据所需自行调整。 秒杀架构: 架构层级 1、一般商家在活动的时候,经常会遇到各种不怀好意的DDOS攻击(利用无辜的吃瓜群众夺取资源),导致真正的我们无法获得服务!所以说高防IP还是很有必要的。 2、搞活动就意味着人多,接入SLB,对多台云服务器进行流量分发,可以通过流量分发扩展应用系统对外的服务能力,通过消除单点故障提升应用系统的可用性。 3、基于SLB价格以及灵活性考虑后面我们接入Nginx限流分发,来保障后端服务的正常运行。 4、后端秒杀业务逻辑,基于Redis 或者 Zookeeper 分布式锁,Kafka 或者 Redis 消息队列,DRDS数据库中间件实现数据的读写分离。 优化思路 1、分流、分流、分流,重要的事情说三遍,再牛逼的机器也抵挡不住高级别的并发。 2、限流、限流、限流,毕竟秒杀商品有限,防刷的前提下没有绝对的公平,根据每个服务的负载能力,设定流量极限。 3、缓存、缓存、缓存、尽量不要让大量请求穿透到DB层,活动开始前商品信息可以推送至分布式缓存。 4、异步、异步、异步,分析并识别出可以异步处理的逻辑,比如日志,缩短系统响应时间。 5、主备、主备、主备,如果有条件好主备容灾方案也是非常有必要的(参考某年锤子的活动被攻击)。 6、最后,为了支撑更高的并发,追求更好的性能,可以对服务器的部署模型进行优化,部分请求走正常的秒杀流程,部分请求直接返回秒杀失败,缺点是开发部署时需要维护两套逻辑。 分层优化 1、前端优化:活动开始前生成静态商品页面推送缓存和CDN,静态文件(JS/CSS)请求推送至文件服务器和CDN。 2、网络优化:如果是全国用户,最好是BGP多线机房,减少网络延迟。 3、应用服务优化:Nginx最佳配置、Tomcat连接池优化、数据库配置优化、数据库连接池优化。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值