1、依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.7.0</version>
</dependency>
2、redis 连接池
public class RedisPoolUtil {
private static volatile JedisPool jedisPool =null;
private RedisPoolUtil(){}
public static JedisPool getJedisPoolInstatnce(){
if (jedisPool ==null){
synchronized (RedisPoolUtil.class){
if (jedisPool == null){
JedisPoolConfig config=new JedisPoolConfig();
config.setMaxTotal(200);
config.setMaxIdle(32);
config.setMaxWaitMillis(100*1000);
config.setBlockWhenExhausted(true);
config.setTestOnBorrow(true);
jedisPool =new JedisPool(config,"127.0.0.1",6379,6000);
}
}
}
return jedisPool;
}
}
3、Service
public class SecKillService {
private static String SecKillScript="local userid=KEYS[1];\n" +
"local prodid=KEYS[2];\n" +
"local uidKey=\"prod:user:\"..userid;\n" +
"local proKey=\"prod:kc:\"..prodid;\n" +
"--redis.log(redis.LOG_NOTICE,uidKey);\n" +
"--判断是否有库存,没有表示未开启秒杀\n" +
"local userExists=redis.call(\"exists\",proKey);\n" +
"if tonumber(userExists)==0 then\n" +
" return \"0\";\n" +
"end\n" +
"--判断库存是否足够,不够停止秒杀\n" +
"local num=redis.call(\"get\",proKey);\n" +
"redis.log(redis.LOG_NOTICE,proKey);\n" +
"if tonumber(num) <=0 then\n" +
" return \"1\";\n" +
"end\n" +
"--判断用户是否已参与过秒杀活动\n" +
"local isMember=redis.call(\"sisMember\",uidKey,userid);\n" +
"if tonumber(isMember)==1 then\n" +
" return \"2\";\n" +
"else\n" +
" redis.call(\"decr\",proKey);\n" +
" redis.call(\"sadd\",uidKey,userid);\n" +
"end\n" +
"return \"3\";";
public boolean secKillByScript(String proId,String uId){
if ("".equals(proId) || null == proId ||"".equals(uId) || null == uId){
return false;
}
Jedis jedis = RedisPoolUtil.getJedisPoolInstatnce().getResource();
String script = jedis.scriptLoad(SecKillScript);
Object evalsha = jedis.evalsha(script, 2, uId, proId);
if ("0".equals(String.valueOf(evalsha))){
System.out.println("未开始");
}else if("1".equals(String.valueOf(evalsha))){
System.out.println("已抢光");
}else if("2".equals(String.valueOf(evalsha))){
System.out.println("已秒杀");
}else if("3".equals(String.valueOf(evalsha))){
System.out.println("秒杀成功");
}
return true;
}
}
jedis连接redis集群
public void test(){
Set<HostAndPort> set =new HashSet<HostAndPort>();
set.add(new HostAndPort("127.0.0.1",6379));
set.add(new HostAndPort("127.0.0.1",6380));
set.add(new HostAndPort("127.0.0.1",6381));
JedisCluster jedisCluster = new JedisCluster(set);
jedisCluster.set("key1","test");
}