码迷,mamicode.com
首页 > 其他好文 > 详细

新零售redis实现秒杀

时间:2020-03-15 09:31:20      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:nts   get   编写   span   new   conf   app   --   multi   

Redis conf

bind 0.0.0.0 允许任何IP访问

daemonize yes 保护进程启动

protected-mode no 关闭保护功能

requirepass no 设置访问密码

开放防火墙

firewall-cmd --zone=public --add-port=80/tcp
firewall-cmd --zone=public --add-port=6379/tcp
firewall-cmd --reload

Redis事务机制,和乐观锁一致

客户端A观察数据,编写命令,批量提交。这三个操作不会被打断,只会出现客户端b修改了数据,客户端a提交数据会失败。

WATCH kill_num kill_user

开启事务命令

MULTI

DECR kill_num

RPUSH kill_user 9502

EXEC

命令行需要先执行discard命令

java模拟代码如下

package demo.test.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-03-15 8:14
 */
public class KillTask implements Runnable{
    @Override
    public void run() {
        Jedis jedis = new Jedis("127.0.0.1",6379);
        jedis.auth("123456");
        jedis.select(0);
        int num = Integer.parseInt(jedis.get("kill_num"));
        if(num>0){
            jedis.watch("kill_num","kill_user");
            Transaction transaction = jedis.multi();
            transaction.decr("kill_num");
            transaction.rpush("kill_user","9527");
            transaction.exec();
        }else {
            Application.pool.shutdown();
        }
        jedis.close();
    }
}
package demo.test.redis;

import redis.clients.jedis.Jedis;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: yangchun
 * @description:
 * @date: Created in 2020-03-15 8:13
 */
public class Application {
    public static ThreadPoolExecutor pool = new ThreadPoolExecutor(
            10,100,10, TimeUnit.SECONDS,new
            LinkedBlockingDeque<Runnable>()
    );
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1",6379);
        jedis.auth("123456");
        jedis.select(0);
        jedis.set("kill_num","50");
        jedis.del("kill_user");
        jedis.close();
        for (int i=0;i<1000;i++){
            pool.execute(new KillTask());
        }
    }
}

 

新零售redis实现秒杀

标签:nts   get   编写   span   new   conf   app   --   multi   

原文地址:https://www.cnblogs.com/xiaofeiyang/p/12495882.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!