org.springframework.data.redis.core.script.RedisScript Java Examples

The following examples show how to use org.springframework.data.redis.core.script.RedisScript. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RqueueMessageTemplateImpl.java    From rqueue with Apache License 2.0 6 votes vote down vote up
@Override
public MessageMoveResult moveMessageZsetToZset(
    String sourceZset,
    String destinationZset,
    int maxMessage,
    long newScore,
    boolean fixedScore) {
  RedisScript<Long> script = (RedisScript<Long>) getScript(ScriptType.MOVE_MESSAGE_ZSET_TO_ZSET);
  long messageInZset = maxMessage;
  int remainingMessages = maxMessage;
  while (messageInZset > 0 && remainingMessages > 0) {
    long messageCount = Math.min(remainingMessages, Constants.MAX_MESSAGES);
    messageInZset =
        scriptExecutor.execute(
            script,
            Arrays.asList(sourceZset, destinationZset),
            messageCount,
            newScore,
            fixedScore);
    remainingMessages -= messageCount;
  }
  return new MessageMoveResult(maxMessage - remainingMessages, true);
}
 
Example #2
Source File: RedisScriptFactory.java    From rqueue with Apache License 2.0 6 votes vote down vote up
static RedisScript getScript(ScriptType type) {
  Resource resource = new ClassPathResource(type.getPath());
  DefaultRedisScript script = new DefaultRedisScript();
  script.setLocation(resource);
  switch (type) {
    case ADD_MESSAGE:
    case MOVE_MESSAGE:
    case PUSH_MESSAGE:
    case MOVE_MESSAGE_LIST_TO_LIST:
    case MOVE_MESSAGE_LIST_TO_ZSET:
    case MOVE_MESSAGE_ZSET_TO_ZSET:
    case MOVE_MESSAGE_ZSET_TO_LIST:
      script.setResultType(Long.class);
      return script;
    case POP_MESSAGE:
      script.setResultType(RqueueMessage.class);
      return script;
    default:
      throw new UnknownSwitchCase(type.toString());
  }
}
 
Example #3
Source File: MessageScheduler.java    From rqueue with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected void initialize() {
  List<String> queueNames = QueueRegistry.getActiveQueues();
  defaultScriptExecutor = new DefaultScriptExecutor<>(redisTemplate);
  redisScript = (RedisScript<Long>) RedisScriptFactory.getScript(ScriptType.PUSH_MESSAGE);
  queueRunningState = new ConcurrentHashMap<>(queueNames.size());
  queueNameToScheduledTask = new ConcurrentHashMap<>(queueNames.size());
  channelNameToQueueName = new ConcurrentHashMap<>(queueNames.size());
  queueNameToLastMessageSeenTime = new ConcurrentHashMap<>(queueNames.size());
  createScheduler(queueNames.size());
  if (isRedisEnabled()) {
    messageSchedulerListener = new MessageSchedulerListener();
  }
  for (String queueName : queueNames) {
    queueRunningState.put(queueName, false);
  }
}
 
Example #4
Source File: RedisSharedLock.java    From ecp-uid with Apache License 2.0 6 votes vote down vote up
@Override
public void close() {
    if (null != scheduledpool && redisTemplate.hasKey(lockKey)) {
        try {
            redisTemplate.execute(new RedisScript<Long>() {
                @Override
                public Class<Long> getResultType() {
                    return Long.class;
                }
                
                @Override
                public String getScriptAsString() {
                    return SCRIPT_UNLOCK;
                }
                
                @Override
                public String getSha1() {
                    return SCRIPT_UNLOCK_SHA1;
                }
            }, Collections.singletonList(lockKey), "1");
        } catch (Exception e) {
            logger.warn(WARN_MSG_EVAL, e.getMessage());
            redisTemplate.delete(lockKey);
        }
    }
}
 
Example #5
Source File: RedisService.java    From SpringMVC-Project with MIT License 5 votes vote down vote up
/**
 * 获取锁
 */
public boolean getLock(String key, String value, int expireTime) {
    String script = "if redis.call('setNX',KEYS[1],ARGV[1]) == 1 then if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end end";

    RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
    Long result = redisTemplate.execute(redisScript, Lists.newArrayList(key), value, expireTime);

    return SUCCESS.equals(result);
}
 
Example #6
Source File: RedisRateLimiter.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
/**
 * Used when setting default configuration in constructor.
 * @param context the ApplicationContext object to be used by this object
 * @throws BeansException if thrown by application context methods
 */
@Override
@SuppressWarnings("unchecked")
public void setApplicationContext(ApplicationContext context) throws BeansException {
	if (initialized.compareAndSet(false, true)) {
		if (this.redisTemplate == null) {
			this.redisTemplate = context.getBean(ReactiveStringRedisTemplate.class);
		}
		this.script = context.getBean(REDIS_SCRIPT_NAME, RedisScript.class);
		if (context.getBeanNamesForType(ConfigurationService.class).length > 0) {
			setConfigurationService(context.getBean(ConfigurationService.class));
		}
	}
}
 
Example #7
Source File: RedisRateLimiter.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
public RedisRateLimiter(ReactiveStringRedisTemplate redisTemplate,
		RedisScript<List<Long>> script, ConfigurationService configurationService) {
	super(Config.class, CONFIGURATION_PROPERTY_NAME, configurationService);
	this.redisTemplate = redisTemplate;
	this.script = script;
	this.initialized.compareAndSet(false, true);
}
 
Example #8
Source File: GatewayRedisAutoConfiguration.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public RedisRateLimiter redisRateLimiter(ReactiveStringRedisTemplate redisTemplate,
		@Qualifier(RedisRateLimiter.REDIS_SCRIPT_NAME) RedisScript<List<Long>> redisScript,
		ConfigurationService configurationService) {
	return new RedisRateLimiter(redisTemplate, redisScript, configurationService);
}
 
Example #9
Source File: GatewayRedisAutoConfiguration.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Bean
@SuppressWarnings("unchecked")
public RedisScript redisRequestRateLimiterScript() {
	DefaultRedisScript redisScript = new DefaultRedisScript<>();
	redisScript.setScriptSource(new ResourceScriptSource(
			new ClassPathResource("META-INF/scripts/request_rate_limiter.lua")));
	redisScript.setResultType(List.class);
	return redisScript;
}
 
Example #10
Source File: RedisConfig.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Bean
@SuppressWarnings("unchecked")
public RedisScript<Long> limitRedisScript() {
    DefaultRedisScript redisScript = new DefaultRedisScript<>();
    redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("scripts/redis/limit.lua")));
    redisScript.setResultType(Long.class);
    return redisScript;
}
 
Example #11
Source File: LimitAspect.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
	HttpServletRequest request = RequestHolder.getHttpServletRequest();
	MethodSignature signature = (MethodSignature) joinPoint.getSignature();
	Method signatureMethod = signature.getMethod();
	Limit limit = signatureMethod.getAnnotation(Limit.class);
	LimitType limitType = limit.limitType();
	String key = limit.key();
	if (StringUtil.isEmpty(key)) {
		if (limitType == LimitType.IP) {
			key = WebUtil.getIp(request);
		} else {
			key = signatureMethod.getName();
		}
	}

	ImmutableList<Object> keys = ImmutableList.of(StringUtil.join(limit.prefix(), "_", key, "_", request.getRequestURI().replaceAll(StringUtil.SLASH, "_")));

	String luaScript = buildLuaScript();
	RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class);
	Number count = redisTemplate.execute(redisScript, keys, limit.count(), limit.period());
	if (null != count && count.intValue() <= limit.count()) {
		logger.info("第{}次访问key为 {},描述为 [{}] 的接口", count, keys, limit.name());
		return joinPoint.proceed();
	} else {
		throw new BadRequestException("访问次数受限制");
	}
}
 
Example #12
Source File: RedisLimitExcutor.java    From distributed-limit with Apache License 2.0 5 votes vote down vote up
@Override
    public LimitResult tryAccess(LimitEntity limitEntity) {
        String identifier = limitEntity.getIdentifier();
//        if (StringUtils.isEmpty( IdentifierThreadLocal.get() )) {
//            identifier = IdentifierThreadLocal.get();
//        }
//        if (StringUtils.isEmpty( identifier )) {
//            throw new LimitException( "identifier cannot be null" );
//        }
        String key =KeyUtil.getKey(limitEntity);
        if (StringUtils.isEmpty(key)) {
            return null;
        }

        int seconds = limitEntity.getSeconds();
        int limitCount = limitEntity.getLimtNum();
       // String compositeKey = KeyUtil.compositeKey( limitEntity.getIdentifier()==null?"nobody":limitEntity.getIdentifier(), limitEntity.getKey() );
        List<String> keys = new ArrayList<>();
        keys.add( key );
        String luaScript = buildLuaScript();
        RedisScript<Long> redisScript = new DefaultRedisScript<>( luaScript, Long.class );
        Long count = stringRedisTemplate.execute( redisScript, keys, "" + limitCount, "" + seconds );
        log.info( "Access try count is {} for key={}", count, key );
//        return count != 0;
        LimitResult result=new LimitResult();
        result.setUrl(key);
        result.setIdenfier(identifier);
        if(count!=0){
           result.setResultType(LimitResult.ResultType.SUCCESS);
        }else {
            result.setResultType(LimitResult.ResultType.FAIL);
        }
        return result;
    }
 
Example #13
Source File: RedisSharedLock.java    From ecp-uid with Apache License 2.0 5 votes vote down vote up
@Override
public boolean lock(int ttl)
    throws RuntimeException {
    this.ttl = ttl;
    // 锁不存在时:上锁并过期时间,最后跳出。
    Long result = redisTemplate.execute(new RedisScript<Long>() {
        @Override
        public String getSha1() {
            return SCRIPT_LOCK_SHA1;
        }
        
        @Override
        public Class<Long> getResultType() {
            return Long.class;
        }
        
        @Override
        public String getScriptAsString() {
            return SCRIPT_LOCK;
        }
        
    }, Collections.singletonList(lockKey), "1", String.valueOf(ttl));
    if (SUCCESS.equals(result)) {
        return true;
    }
    return false;
}
 
Example #14
Source File: LimitAspect.java    From eladmin with Apache License 2.0 5 votes vote down vote up
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    HttpServletRequest request = RequestHolder.getHttpServletRequest();
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method signatureMethod = signature.getMethod();
    Limit limit = signatureMethod.getAnnotation(Limit.class);
    LimitType limitType = limit.limitType();
    String key = limit.key();
    if (StringUtils.isEmpty(key)) {
        if (limitType == LimitType.IP) {
            key = StringUtils.getIp(request);
        } else {
            key = signatureMethod.getName();
        }
    }

    ImmutableList<Object> keys = ImmutableList.of(StringUtils.join(limit.prefix(), "_", key, "_", request.getRequestURI().replaceAll("/","_")));

    String luaScript = buildLuaScript();
    RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class);
    Number count = redisTemplate.execute(redisScript, keys, limit.count(), limit.period());
    if (null != count && count.intValue() <= limit.count()) {
        logger.info("第{}次访问key为 {},描述为 [{}] 的接口", count, keys, limit.name());
        return joinPoint.proceed();
    } else {
        throw new BadRequestException("访问次数受限制");
    }
}
 
Example #15
Source File: RedisService.java    From SpringMVC-Project with MIT License 5 votes vote down vote up
/**
 * 解锁
 */
public boolean releaseLock(String key, String value) {
    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

    RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
    Long result = redisTemplate.execute(redisScript, Lists.newArrayList(key), value);

    return SUCCESS.equals(result);
}
 
Example #16
Source File: RateLimiterAutoConfiguration.java    From mica with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private RedisScript<List<Long>> redisRateLimiterScript() {
	DefaultRedisScript redisScript = new DefaultRedisScript<>();
	redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("META-INF/scripts/mica_rate_limiter.lua")));
	redisScript.setResultType(List.class);
	return redisScript;
}
 
Example #17
Source File: RedisLuaRateLimiter.java    From api-boot with Apache License 2.0 5 votes vote down vote up
/**
 * get Redis Script
 *
 * @return RedisScript
 */
RedisScript<List<Long>> getRedisScript() {
    DefaultRedisScript redisScript = new DefaultRedisScript<>();
    redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource(QPS_LUA_PATH)));
    redisScript.setResultType(List.class);
    return redisScript;
}
 
Example #18
Source File: LimitAspect.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    HttpServletRequest request = RequestHolder.getHttpServletRequest();
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method signatureMethod = signature.getMethod();
    Limit limit = signatureMethod.getAnnotation(Limit.class);
    LimitType limitType = limit.limitType();
    String key = limit.key();
    if (StringUtils.isEmpty(key)) {
        if (limitType == LimitType.IP) {
            key = StringUtils.getIp(request);
        } else {
            key = signatureMethod.getName();
        }
    }

    ImmutableList<Object> keys = ImmutableList.of(StringUtils.join(limit.prefix(), "_", key, "_", request.getRequestURI().replaceAll("/","_")));

    String luaScript = buildLuaScript();
    RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class);
    Number count = redisTemplate.execute(redisScript, keys, limit.count(), limit.period());
    if (null != count && count.intValue() <= limit.count()) {
        logger.info("第{}次访问key为 {},描述为 [{}] 的接口", count, keys, limit.name());
        return joinPoint.proceed();
    } else {
        throw new BadRequestException("访问次数受限制");
    }
}
 
Example #19
Source File: AbstractResourceLimiter.java    From easy-sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * @param script            lua脚本
 * @param redisScriptOption redis操作lua参数
 * @return true: 限流 , false: 不限流
 */
private boolean callbackCommand(String script, RedisScriptOption redisScriptOption) {
    Long currentCount = (Long) redisTemplate.execute(RedisScript.of(script, Long.class), redisScriptOption.getKeys(), redisScriptOption.argvs());
    if (currentCount == 0) {
        log.error("Current resource access exceeds maximum limit");
    } else {
        log.debug("Current resource access QPS =" + currentCount);
    }
    return currentCount == 0;
}
 
Example #20
Source File: RateCheckRedisRateLimiter.java    From momo-cloud-permission with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void setApplicationContext(ApplicationContext context) throws BeansException {
    if (initialized.compareAndSet(false, true)) {
        this.redisTemplate = context.getBean("stringReactiveRedisTemplate", ReactiveRedisTemplate.class);
        this.script = context.getBean(REDIS_SCRIPT_NAME, RedisScript.class);
        if (context.getBeanNamesForType(Validator.class).length > 0) {
            this.setValidator(context.getBean(Validator.class));
        }
    }
}
 
Example #21
Source File: RateCheckRedisRateLimiter.java    From momo-cloud-permission with Apache License 2.0 5 votes vote down vote up
public RateCheckRedisRateLimiter(ReactiveRedisTemplate<String, String> redisTemplate,
                                 RedisScript<List<Long>> script, Validator validator) {
    super(Config.class, CONFIGURATION_PROPERTY_NAME, validator);
    this.redisTemplate = redisTemplate;
    this.script = script;
    initialized.compareAndSet(false, true);
}
 
Example #22
Source File: RqueueMessageTemplateImpl.java    From rqueue with Apache License 2.0 5 votes vote down vote up
@Override
public MessageMoveResult moveMessageListToZset(
    String sourceList, String destinationZset, int maxMessage, long score) {
  RedisScript<Long> script = (RedisScript<Long>) getScript(ScriptType.MOVE_MESSAGE_LIST_TO_ZSET);
  long messagesInList = maxMessage;
  int remainingMessages = maxMessage;
  while (messagesInList > 0 && remainingMessages > 0) {
    long messageCount = Math.min(remainingMessages, Constants.MAX_MESSAGES);
    messagesInList =
        scriptExecutor.execute(
            script, Arrays.asList(sourceList, destinationZset), messageCount, score);
    remainingMessages -= messageCount;
  }
  return new MessageMoveResult(maxMessage - remainingMessages, true);
}
 
Example #23
Source File: RqueueMessageTemplateImpl.java    From rqueue with Apache License 2.0 5 votes vote down vote up
private MessageMoveResult moveMessageToList(
    String src, String dst, int maxMessage, ScriptType scriptType) {
  RedisScript<Long> script = (RedisScript<Long>) getScript(scriptType);
  long messagesInSrc = maxMessage;
  int remainingMessages = maxMessage;
  while (messagesInSrc > 0 && remainingMessages > 0) {
    long messageCount = Math.min(remainingMessages, Constants.MAX_MESSAGES);
    messagesInSrc = scriptExecutor.execute(script, Arrays.asList(src, dst), messageCount);
    remainingMessages -= messageCount;
  }
  return new MessageMoveResult(maxMessage - remainingMessages, true);
}
 
Example #24
Source File: RqueueMessageTemplateImpl.java    From rqueue with Apache License 2.0 5 votes vote down vote up
@Override
public void moveMessage(
    String srcZsetName, String tgtZsetName, RqueueMessage src, RqueueMessage tgt, long delay) {
  RedisScript<Long> script = (RedisScript<Long>) getScript(ScriptType.MOVE_MESSAGE);
  Long response =
      scriptExecutor.execute(
          script,
          Arrays.asList(srcZsetName, tgtZsetName),
          src,
          tgt,
          System.currentTimeMillis() + delay);
  if (response == null) {
    log.error("Duplicate processing for the message {}", src);
  }
}
 
Example #25
Source File: RqueueMessageTemplateImpl.java    From rqueue with Apache License 2.0 5 votes vote down vote up
@Override
public Long addMessageWithDelay(
    String delayQueueName, String delayQueueChannelName, RqueueMessage rqueueMessage) {
  long queuedTime = rqueueMessage.getQueuedTime();
  RedisScript<Long> script = (RedisScript<Long>) getScript(ScriptType.ADD_MESSAGE);
  return scriptExecutor.execute(
      script,
      Arrays.asList(delayQueueName, delayQueueChannelName),
      rqueueMessage,
      rqueueMessage.getProcessAt(),
      queuedTime);
}
 
Example #26
Source File: RqueueMessageTemplateImpl.java    From rqueue with Apache License 2.0 5 votes vote down vote up
@Override
public RqueueMessage pop(
    String queueName,
    String processingQueueName,
    String processingChannelName,
    long visibilityTimeout) {
  long currentTime = System.currentTimeMillis();
  RedisScript<RqueueMessage> script =
      (RedisScript<RqueueMessage>) getScript(ScriptType.POP_MESSAGE);
  return scriptExecutor.execute(
      script,
      Arrays.asList(queueName, processingQueueName, processingChannelName),
      currentTime,
      currentTime + visibilityTimeout);
}
 
Example #27
Source File: RateLimiterAutoConfiguration.java    From mica with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public RedisRateLimiterClient redisRateLimiter(StringRedisTemplate redisTemplate,
											   Environment environment) {
	RedisScript<List<Long>> redisRateLimiterScript = redisRateLimiterScript();
	return new RedisRateLimiterClient(redisTemplate, redisRateLimiterScript, environment);
}
 
Example #28
Source File: DefaultRedisRateLimiter.java    From JetfireCloud with Apache License 2.0 4 votes vote down vote up
public DefaultRedisRateLimiter(ReactiveRedisTemplate<String, String> redisTemplate, RedisScript<List<Long>> script, Validator validator) {
    super(redisTemplate, script, validator);
}
 
Example #29
Source File: DefaultIdGeneratorPolicy.java    From x7 with Apache License 2.0 4 votes vote down vote up
@Override
public void onStart(List<BaseRepository> repositoryList) {
    if (repositoryList == null)
        return;

    long startTme = System.currentTimeMillis();
    logger.info("x7-repo/x7-id-generator starting.... \n");

    final String idGeneratorScript = "local hk = KEYS[1] " +
            "local key = KEYS[2] " +
            "local id = ARGV[1] " +
            "local existId = redis.call('hget',hk,key) " +
            "if tonumber(id) > tonumber(existId) " +
            "then " +
            "redis.call('hset',hk,key,tostring(id)) " +
            "return tonumber(id) "+
            "end " +
            "return tonumber(existId)";

    RedisScript<Long> redisScript = new DefaultRedisScript<Long>() {

        @Override
        public String getSha1(){
            return VerifyUtil.toMD5("id_map_key");
        }

        @Override
        public Class<Long> getResultType() {
            return Long.class;
        }

        @Override
        public String getScriptAsString() {
            return  idGeneratorScript;
        }
    };

    for (BaseRepository baseRepository : repositoryList) {
        CriteriaBuilder.ResultMappedBuilder builder = CriteriaBuilder.buildResultMapped();
        Class clzz = baseRepository.getClz();
        Parsed parsed = Parser.get(clzz);
        String key = parsed.getKey(X.KEY_ONE);
        BeanElement be = parsed.getElement(key);
        if (be.clz == String.class)
            continue;
        builder.reduce(ReduceType.MAX, be.property).paged().ignoreTotalRows();
        Criteria.ResultMappedCriteria resultMappedCriteria = builder.get();

        List<Long> idList = baseRepository.listPlainValue(Long.class,resultMappedCriteria);
        Long maxId = idList.stream().filter(id -> id != null).findFirst().orElse(0L);
        String name = baseRepository.getClz().getName();

        logger.info("Db    : " + name + ".maxId = " + maxId);

        List<String> keys = Arrays.asList(IdGeneratorPolicy.ID_MAP_KEY,name);
        long result = this.stringRedisTemplate.execute(redisScript,keys,String.valueOf(maxId));

        logger.info("Redis : " + name + ".maxId = " + result);

    }
    logger.info("..................................................");
    long endTime = System.currentTimeMillis();
    logger.info("x7-repo/x7-id-generator started, cost time: " + (endTime-startTme) +"ms\n\n");
}
 
Example #30
Source File: DefaultRedisRateLimiter.java    From SpringCloud with Apache License 2.0 4 votes vote down vote up
public DefaultRedisRateLimiter(ReactiveRedisTemplate<String, String> redisTemplate,
                               RedisScript<List<Long>> script,
                               @Qualifier("defaultValidator") Validator validator) {
    super(redisTemplate, script, validator);
}