v1
function v1() {
$amountLimit = 100;
// ...
}
PHP function
Linux Redis PHP Nginx
setnx命令如果key已经存在则不进行任何操作(当然也不会覆盖,但是set命令会覆盖),不存在则新建key
PHPDemo,参考价值不大。
v2支持并发
对图一增加 $redis->incrby($keyName,$currAmount);
v1版本 缺陷版本
初始化95 ???
import redis.clients.jedis.Jedis; /** * 2018/11/6 11:57 */ public class CountThread extends Thread { public static void main(String args[]) { MyThread thread1 = new MyThread(); thread1.setName("线程1"); MyThread thread2 = new MyThread(); thread2.setName("线程2"); Jedis jedis = new Jedis("localhost", 6379); jedis.del("myCounter");//每次初始删除key jedis.close(); thread1.start(); thread2.start(); //可以多设立几个线程,方便查看异常结果 } } class MyThread extends Thread { final int amountLimit = 100;//总库存量 String keyName = "myCounter";//redis key Name @Override public void run() { //每个线程执行7次 for (int i = 0; i < 7; i++) { v1(); } } //计数器v1 public void v1() { Jedis jedis = new Jedis("localhost", 6379); int incrAmount = 1;//每次incr大小 if (!jedis.exists(keyName)) { jedis.set(keyName, String.valueOf(95)); } int currentAmount = Integer.parseInt(jedis.get(keyName)); if (currentAmount + incrAmount > amountLimit) { System.out.println(Thread.currentThread() + "Bad luck!v1"); } else { jedis.incrBy(keyName, incrAmount); System.out.println(Thread.currentThread() + "Good Luck!v1"); } jedis.close(); } //计数器v2 public void v2() { Jedis jedis = new Jedis("localhost", 6379); int incrAmount = 1; if (!jedis.exists(keyName)) { jedis.setnx(keyName, String.valueOf(95)); } if (jedis.incrBy(keyName, incrAmount) > amountLimit) { jedis.decrBy(keyName, incrAmount);//超额回滚 System.out.println(Thread.currentThread() + "Bad luck!v2"); } else { System.out.println(Thread.currentThread() + "Good Luck!v2"); } jedis.close(); } }
有什么问题欢迎讨论