Created
February 16, 2014 10:39
-
-
Save hengyunabc/9032295 to your computer and use it in GitHub Desktop.
redis全局ID生成脚本的测试程序,注意要使用jedis2.4.0以上。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.test; | |
import java.util.List; | |
import java.util.Random; | |
import java.util.concurrent.CountDownLatch; | |
import org.springframework.util.StopWatch; | |
import redis.clients.jedis.Jedis; | |
public class TestIdGenenator { | |
static String host = "localhost"; | |
static int threadCount = 20; | |
static int genCount = 10000; | |
static StopWatch watch = new StopWatch(); | |
static final String script = "local step = redis.call('GET', 'idgenerator_step');\n" | |
+ "local shardId = KEYS[1] % 1024;\n" | |
+ "local next = redis.call('INCRBY', 'idgenerator_next_' .. shardId, step);\n" | |
+ "return {math.currentMiliseconds(), shardId, next};\n"; | |
public static void main(String[] args) throws InterruptedException { | |
test(); | |
// testOne(); | |
} | |
static public void testOne() { | |
Jedis jedis = new Jedis(host); | |
Object object = jedis.eval(script, 1, "1"); | |
System.err.println("object:" + object); | |
List result = (List)object; | |
System.err.println("pc miliSeconds:" + System.currentTimeMillis()); | |
System.err.println(" miliSeconds:" + (long)result.get(0)); | |
System.err.println("shardingId:" + (long)result.get(1)); | |
System.err.println("next:" + result.get(2)); | |
} | |
static public void test() throws InterruptedException { | |
{ | |
Jedis jedis = new Jedis(host); | |
jedis.flushAll(); | |
jedis.set("idgenerator_step", "2"); | |
jedis.set("idgenerator_next", "1"); | |
} | |
final CountDownLatch latch = new CountDownLatch(threadCount); | |
watch.start(); | |
for(int i = 0; i < threadCount; ++i) { | |
Thread thread = new Thread() { | |
public void run() { | |
Jedis jedis = new Jedis(host); | |
for(int j = 0; j < genCount; ++j) { | |
jedis.eval(script, 1, "" + j); | |
} | |
latch.countDown(); | |
} | |
}; | |
thread.start(); | |
} | |
latch.await(); | |
watch.stop(); | |
System.err.println("time:" + watch.getTotalTimeSeconds()); | |
System.err.println("speed:" + genCount * threadCount / watch.getTotalTimeSeconds()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment