package ssm;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.util.StopWatch;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
* @author: liuyafei
* @date 创建时间:2016年1月15日 下午5:33:31
* @version 1.0
* @parameter
* @return
*/
public class TestEval {
static String host = "192.168.1.31";
static Random random = new Random();
static StopWatch watch = new StopWatch();
//参数: 编号 金额
static String changeMoneyScript =
"local money = tonumber(redis.call('get', KEYS[1]));"
+"print(money);\n"
+"if money <=0 then\n"
+" return nil\n"
+"else\n"
+" money=money-tonumber(KEYS[2]);\n"
+" if money<0 then\n"
+" return nil\n"
+" else\n"
+" redis.call('set', KEYS[1],money);"
+" return money;\n"
+" end\n"
+"end\n"
+ "return nil";
public static void main(String[] args) throws InterruptedException {
// 初始化信息
final JedisPool pool = RedisAPI.getPool();
Jedis jedis = pool.getResource();
jedis.flushAll();
jedis.set("hongbao", "100000");
System.out.println(1);
pool.returnResource(jedis);
//模拟1万个用户 并发300去抢红包
watch.start();
int threadCount=99999;
final CountDownLatch latch = new CountDownLatch(threadCount);
ExecutorService exec = Executors.newFixedThreadPool(300);
for (int index = 0; index <threadCount ; index++) {
final int a = index;
Runnable run = new Runnable() {
public void run() {
Jedis jedis=null;
try {
jedis = pool.getResource();
String sha = jedis.scriptLoad(changeMoneyScript);
Object object = jedis.eval(changeMoneyScript,2,"hongbao", "1");
System.out.println("object="+object);
} catch (Exception e) {
e.printStackTrace();
}finally{
pool.returnResource(jedis);
}
latch.countDown();
}
};
exec.execute(run);
}
// 退出线程池
exec.shutdown();
latch.await();
watch.stop();
System.err.println("time:" + watch.getTotalTimeSeconds());
System.err.println("speed:" + threadCount/watch.getTotalTimeSeconds());
System.err.println("end:" + System.currentTimeMillis()/1000);
}
}
转载于:https://my.oschina.net/yafeiok/blog/604397