新零售redis实现秒杀
Posted 清浊
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了新零售redis实现秒杀相关的知识,希望对你有一定的参考价值。
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实现秒杀的主要内容,如果未能解决你的问题,请参考以下文章