|
@@ -0,0 +1,48 @@
|
|
|
+package com.alvin;
|
|
|
+
|
|
|
+
|
|
|
+import com.alvin.util.FileUtil;
|
|
|
+import redis.clients.jedis.Jedis;
|
|
|
+import redis.clients.jedis.JedisPool;
|
|
|
+import redis.clients.jedis.JedisPoolConfig;
|
|
|
+
|
|
|
+import java.io.UnsupportedEncodingException;
|
|
|
+import java.util.Arrays;
|
|
|
+
|
|
|
+public class JedisUtil {
|
|
|
+ public static volatile JedisPool pool;
|
|
|
+ public static String luaStr = "";
|
|
|
+
|
|
|
+ static {
|
|
|
+ JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
|
|
|
+ jedisPoolConfig.setMinIdle(4); // 初始化数
|
|
|
+ jedisPoolConfig.setMaxIdle(8); // 最大空闲数
|
|
|
+ jedisPoolConfig.setMaxTotal(10); // 最大连接数
|
|
|
+ pool = new JedisPool(jedisPoolConfig, "127.0.0.1", 6379);
|
|
|
+ try {
|
|
|
+ luaStr = FileUtil.readToString("redis.lua");
|
|
|
+ } catch (UnsupportedEncodingException e) {
|
|
|
+ throw new RuntimeException(e);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 获取令牌
|
|
|
+ *
|
|
|
+ * @param key 请求id
|
|
|
+ * @param max 最大能同时承受多少的并发(桶容量)
|
|
|
+ * @param rate 每秒生成多少的令牌
|
|
|
+ * @return 获取令牌返回true,没有获取返回false
|
|
|
+ */
|
|
|
+ public static boolean tryAcquire(String key, int max, int rate) {
|
|
|
+ try (Jedis jedis = pool.getResource()) {
|
|
|
+ return Long.valueOf(1).equals(
|
|
|
+ jedis.evalsha(jedis.scriptLoad(luaStr),
|
|
|
+ Arrays.asList(key),
|
|
|
+ Arrays.asList(Integer.toString(max), Integer.toString(rate), Long.toString(System.currentTimeMillis())))
|
|
|
+ );
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+}
|