servlet

  1. package com.manster;
  2. import java.io.IOException;
  3. import java.util.Random;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. public class SecKillServlet extends HttpServlet {
  9. private static final long serialVersionUID = 1L;
  10. public SecKillServlet() {
  11. super();
  12. }
  13. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  14. String userid = new Random().nextInt(50000) +"" ;
  15. String prodid =request.getParameter("prodid");
  16. boolean isSuccess=SecKill_redis.doSecKill(userid,prodid);
  17. response.getWriter().print(isSuccess);
  18. }
  19. }

jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>秒杀</title>
  8. </head>
  9. <body>
  10. <h1>iPaid Pro 2021 !!! 1元秒杀!!!
  11. </h1>
  12. <form id="msform" action="${pageContext.request.contextPath}/doseckill" enctype="application/x-www-form-urlencoded">
  13. <input type="hidden" id="prodid" name="prodid" value="0101">
  14. <input type="button" id="miaosha_btn" name="seckill_btn" value="秒杀点我"/>
  15. </form>
  16. </body>
  17. <script type="text/javascript" src="${pageContext.request.contextPath}/script/jquery/jquery-3.1.0.js"></script>
  18. <script type="text/javascript">
  19. $(function(){
  20. $("#miaosha_btn").click(function(){
  21. var url=$("#msform").attr("action");
  22. $.post(url,$("#msform").serialize(),function(data){
  23. if(data=="false"){
  24. alert("抢光了" );
  25. $("#miaosha_btn").attr("disabled",true);
  26. }
  27. } );
  28. })
  29. })
  30. </script>
  31. </html>

秒杀操作

  1. package com.manster;
  2. import java.io.IOException;
  3. import java.util.List;
  4. import redis.clients.jedis.Jedis;
  5. import redis.clients.jedis.JedisPool;
  6. import redis.clients.jedis.Transaction;
  7. public class SecKill_redis {
  8. public static void main(String[] args) {
  9. Jedis jedis =new Jedis("192.168.44.168",6379);
  10. System.out.println(jedis.pmiaoing());
  11. jedis.close();
  12. }
  13. //秒杀过程
  14. public static boolean doSecKill(String uid,String prodid) throws IOException {
  15. //1 uid和prodid非空判断
  16. if(uid == null || prodid==null){
  17. return false;
  18. }
  19. //2 连接redis
  20. Jedis jedis = new Jedis("192.168.75.11", 6379);
  21. //3 拼接key
  22. // 3.1 库存key
  23. String stockKey = "stock" + prodid;
  24. // 3.2 秒杀成功用户key
  25. String userKey = "user" + uid;
  26. //4 获取库存,如果库存null,秒杀还没有开始
  27. String stock = jedis.get(stockKey);
  28. if(stock == null){
  29. System.out.println("秒杀未开始,请等待");
  30. jedis.close();
  31. return false;
  32. }
  33. // 5 判断用户是否重复秒杀操作
  34. Boolean sismember = jedis.sismember(userKey, uid);
  35. if(sismember){
  36. System.out.println("已经秒杀成功,不可重复秒杀!");
  37. jedis.close();
  38. return false;
  39. }
  40. //6 判断如果商品数量,库存数量小于1,秒杀结束
  41. if(Integer.parseInt(stock) <= 0){
  42. System.out.println("秒杀结束");
  43. jedis.close();
  44. return false;
  45. }
  46. //7 秒杀过程
  47. //7.1 库存-1
  48. jedis.decr(stockKey);
  49. //7.2 把秒杀成功用户添加清单里面
  50. jedis.sadd(userKey,uid);
  51. System.out.println("秒杀成功");
  52. jedis.close();
  53. return true;
  54. }
  55. }
  56. 点击秒杀:
  57. 秒杀成功
  58. 秒杀成功
  59. 秒杀成功
  60. 秒杀成功
  61. 秒杀成功
  62. 秒杀结束
  63. 127.0.0.1:6379> set stock0101 5
  64. OK
  65. 127.0.0.1:6379> keys *
  66. 1) "user44536"
  67. 2) "stock0101"
  68. 3) "user37862"
  69. 4) "user6828"
  70. 5) "user48084"
  71. 6) "user45439"
  72. 127.0.0.1:6379> smembers user44536
  73. 1) "44536"
  74. 127.0.0.1:6379> get stock0101
  75. "0"

1、解决计数器和人员记录的事务操作

image.png

2、Redis事务—秒杀并发模拟

使用工具ab模拟测试
CentOS6 默认安装
CentOS7需要手动安装

1、下载工具

**yum install httpd-tools**

2、工具简介

    -n requests     要执行的请求数
    -c concurrency  一次发出的多个请求数

    -p postfile     包含要POST的数据的文件。还记得设置-T

    -T content-type 用于POST/PUT数据的内容类型标头,例如。“application/x-www-form-urlencoded”,
                                    默认是“text/plain”
        -r              socket接收错误时不退出。

3、测试及结果

1、通过ab测试
vim postfile 模拟表单提交参数,以&符号结尾;存放当前目录。

[root@localhost ~]# vim postfile01
prodid=0101&

ab -n 1000 -c 100 -p  ~/postfile01 -T application/x-www-form-urlencoded http://123.175.195.7:8888/Seckill/doseckill
1000次请求,100并发(100个人每人发10次)

127.0.0.1:6379> set stock0101 10
OK

秒杀成功
秒杀成功
秒杀结束
秒杀成功
秒杀成功
秒杀成功
秒杀结束
秒杀结束
秒杀成功
秒杀结束

http://123.175.195.7:8888/Seckill/doseckill

127.0.0.1:6379> get stock0101
"-1"

产生了超卖
连接超时

3、超卖问题

image.png

4、利用乐观锁淘汰用户,解决超卖问题

image.png
1、监视库存

        jedis.watch(stockKey);

2、添加事务

        //7 秒杀过程
        //使用事务
        Transaction multi = jedis.multi();

        //组队
        multi.decr(stockKey);
        multi.sadd(userKey,uid);

        //执行
        List<Object> result = multi.exec();

        if(result == null || result.size()==0){
            System.err.println("秒杀失败");
            jedis.close();
            return false;
        }

        System.out.println("秒杀成功");
        jedis.close();
        return true;

3、继续测试

127.0.0.1:6379> set stock0101 10
OK
127.0.0.1:6379> get stock0101
"10"
127.0.0.1:6379> keys *
 1) "user3948"
 2) "user25607"
 3) "user40920"
 4) "user46811"
 5) "user24878"
 6) "user22643"
 7) "stock0101"
 8) "user44606"
 9) "user39658"
10) "user39082"
11) "user8588"
127.0.0.1:6379> get stock0101
"0"

5、继续增加并发测试

1、连接有限制

[root@localhost ~]# ab -n 2000 -c 300 -p ~/postfile01 -T application/x-www-form-urlencoded [http://123.175.195.7:8888/Seckill/doseckill](http://123.175.195.7:8888/Seckill/doseckill)

增加-r参数,-r Don’t exit on socket receive errors.
[root@localhost ~]# ab -n 2000 -c 300 -r -p ~/postfile01 -T application/x-www-form-urlencoded [http://123.175.195.7:8888/Seckill/doseckill](http://123.175.195.7:8888/Seckill/doseckill)

2、已经秒光,可是还有库存

[root@localhost ~]# ab -n 2000 -c 300 -p ~/postfile01 -T application/x-www-form-urlencoded [http://123.175.195.7:8888/Seckill/doseckill](http://123.175.195.7:8888/Seckill/doseckill)
已经秒光,可是还有库存。原因,就是乐观锁导致很多请求都失败。先点的没秒到,后点的可能秒到了。

127.0.0.1:6379> get stock0101
"312"

3、连接超时,通过连接池解决

package com.manster;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolUtil {
    private static volatile JedisPool jedisPool = null;

    private JedisPoolUtil() {
    }

    public static JedisPool getJedisPoolInstance() {
        if (null == jedisPool) {
            synchronized (JedisPoolUtil.class) {
                if (null == jedisPool) {
                    JedisPoolConfig poolConfig = new JedisPoolConfig();
                    poolConfig.setMaxTotal(200);
                    poolConfig.setMaxIdle(32);
                    poolConfig.setMaxWaitMillis(100*1000);
                    poolConfig.setBlockWhenExhausted(true);
                    poolConfig.setTestOnBorrow(true);  // ping  PONG

                    jedisPool = new JedisPool(poolConfig, "192.168.75.11", 6379, 60000 );
                }
            }
        }
        return jedisPool;
    }

    public static void release(JedisPool jedisPool, Jedis jedis) {
        if (null != jedis) {
            jedisPool.returnResource(jedis);
        }
    }

}
        JedisPool jedisPoolInstance = JedisPoolUtil.getJedisPoolInstance();
        Jedis jedis = jedisPoolInstance.getResource();

4、连接池

节省每次连接redis服务带来的消耗,把连接好的实例反复利用。
通过参数管理连接的行为

package com.manster;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolUtil {
    private static volatile JedisPool jedisPool = null;

    private JedisPoolUtil() {
    }

    public static JedisPool getJedisPoolInstance() {
        if (null == jedisPool) {
            synchronized (JedisPoolUtil.class) {
                if (null == jedisPool) {
                    JedisPoolConfig poolConfig = new JedisPoolConfig();
                    poolConfig.setMaxTotal(200);
                    poolConfig.setMaxIdle(32);
                    poolConfig.setMaxWaitMillis(100*1000);
                    poolConfig.setBlockWhenExhausted(true);
                    poolConfig.setTestOnBorrow(true);  // ping  PONG

                    jedisPool = new JedisPool(poolConfig, "192.168.75.11", 6379, 60000 );
                }
            }
        }
        return jedisPool;
    }

    public static void release(JedisPool jedisPool, Jedis jedis) {
        if (null != jedis) {
            jedisPool.returnResource(jedis);
        }
    }

}

连接池参数

  • MaxTotal:控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;如果赋值为-1,则表示不限制;如果pool已经分配了MaxTotal个jedis实例,则此时pool的状态为exhausted。
  • maxIdle:控制一个pool最多有多少个状态为idle(空闲)的jedis实例;
  • MaxWaitMillis:表示当borrow一个jedis实例时,最大的等待毫秒数,如果超过等待时间,则直接抛JedisConnectionException;
  • testOnBorrow:获得一个jedis实例的时候是否检查连接可用性(ping());如果为true,则得到的jedis实例均是可用的;

    6、解决库存遗留问题

    1、LUA脚本

    Lua 是一个小巧的脚本语言,Lua脚本可以很容易的被C/C++ 代码调用,也可以反过来调用C/C++的函数,Lua并没有提供强大的库,一个完整的Lua解释器不过200k,所以Lua不适合作为开发独立应用程序的语言,而是作为嵌入式脚本语言。
    很多应用程序、游戏使用LUA作为自己的嵌入式脚本语言,以此来实现可配置性、可扩展性。
    这其中包括魔兽争霸地图、魔兽世界、博德之门、愤怒的小鸟等众多游戏插件或外挂。
    https://www.w3cschool.cn/lua/

    2、LUA脚本在Redis中的优势

将复杂的或者多步的redis操作,写为一个脚本,一次提交给redis执行,减少反复连接redis的次数。提升性能。
LUA脚本是类似redis事务,有一定的原子性,不会被其他命令插队,可以完成一些redis事务性的操作。
但是注意redis的lua脚本功能,只有在Redis 2.6以上的版本才可以使用。
利用lua脚本淘汰用户,解决超卖问题。
redis 2.6版本以后,通过lua脚本解决争抢问题,实际上是redis 利用其单线程的特性,用任务队列的方式解决多任务并发问题
image.png
lua脚本

local userid=KEYS[1]; 
local prodid=KEYS[2];
local stockKey= "stock"..prodid;
local usersKey="user"..userid; 
local userExists=redis.call("sismember",usersKey,userid);
if tonumber(userExists)==1 then 
  return 2;
end
local num= redis.call("get" ,stockKey);
if tonumber(num)<=0 then 
  return 0; 
else 
  redis.call("decr",stockKey);
  redis.call("sadd",usersKey,userid);
end
return 1;

java中使用lua脚本(记得要在servlet中更改doSecKill函数)

package com.manster;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.slf4j.LoggerFactory;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class SecKill_redisByScript {

    private static final  org.slf4j.Logger logger =LoggerFactory.getLogger(SecKill_redisByScript.class) ;

    public static void main(String[] args) throws IOException {
        JedisPool jedispool =  JedisPoolUtil.getJedisPoolInstance();

        Jedis jedis=jedispool.getResource();
        System.out.println(jedis.ping());

        Set<HostAndPort> set=new HashSet<HostAndPort>();

        doSecKill("201","sk:0101");
    }

    static String secKillScript ="local userid=KEYS[1];\r\n" + 
            "local prodid=KEYS[2];\r\n" + 
            "local stockKey='stock'..prodid;\r\n" +
            "local usersKey='user'..userid;\r\n" +
            "local userExists=redis.call(\"sismember\",usersKey,userid);\r\n" + 
            "if tonumber(userExists)==1 then \r\n" + 
            "   return 2;\r\n" + 
            "end\r\n" + 
            "local num= redis.call(\"get\" ,stockKey);\r\n" +
            "if tonumber(num)<=0 then \r\n" + 
            "   return 0;\r\n" + 
            "else \r\n" + 
            "   redis.call(\"decr\",stockKey);\r\n" +
            "   redis.call(\"sadd\",usersKey,userid);\r\n" + 
            "end\r\n" + 
            "return 1" ;

    static String secKillScript2 = 
            "local userExists=redis.call(\"sismember\",\"stock0101\",userid);\r\n" +
            " return 1";

    public static boolean doSecKill(String uid,String prodid) throws IOException {

        JedisPool jedispool =  JedisPoolUtil.getJedisPoolInstance();
        Jedis jedis=jedispool.getResource();

         //String sha1=  .secKillScript;
        String sha1=  jedis.scriptLoad(secKillScript);
        Object result= jedis.evalsha(sha1, 2, uid,prodid);

          String reString=String.valueOf(result);
        if ("0".equals( reString )  ) {
            System.err.println("已抢空!!");
        }else if("1".equals( reString )  )  {
            System.out.println("抢购成功!!!!");
        }else if("2".equals( reString )  )  {
            System.err.println("该用户已抢过!!");
        }else{
            System.err.println("抢购异常!!");
        }
        jedis.close();
        return true;
    }
}

测试结果

[root@localhost ~]# ab -n 2000 -c 300 -p  ~/postfile01 -T application/x-www-form-urlencoded http://123.175.195.7:8888/Seckill/doseckill


127.0.0.1:6379> set stock0101 500
OK
127.0.0.1:6379> get stock0101
"0"

7、版本

1、简单版

点10次,正常秒杀
一起点试一试,秒杀也是正常的。这是因为还达不到并发的效果。
使用工具ab模拟并发测试,会出现超卖情况。查看库存会出现负数。

2、加事务-乐观锁(解决超卖),但出现遗留库存和连接超时

3、连接池解决超时问题

4、解决库存依赖问题,LUA脚本