| | |
| | | package com.ruoyi.framework.config; |
| | | |
| | | import cn.hutool.core.util.StrUtil; |
| | | import com.ruoyi.common.utils.StringUtils; |
| | | import com.ruoyi.framework.config.properties.RedissonProperties; |
| | | import org.redisson.Redisson; |
| | | import org.redisson.api.RedissonClient; |
| | |
| | | .setAddress(prefix + redisProperties.getHost() + ":" + redisProperties.getPort()) |
| | | .setConnectTimeout(((Long) redisProperties.getTimeout().toMillis()).intValue()) |
| | | .setDatabase(redisProperties.getDatabase()) |
| | | .setPassword(StrUtil.isNotBlank(redisProperties.getPassword()) ? redisProperties.getPassword() : null) |
| | | .setPassword(StringUtils.isNotBlank(redisProperties.getPassword()) ? redisProperties.getPassword() : null) |
| | | .setTimeout(singleServerConfig.getTimeout()) |
| | | .setRetryAttempts(singleServerConfig.getRetryAttempts()) |
| | | .setRetryInterval(singleServerConfig.getRetryInterval()) |
| | |
| | | return new RedissonSpringCacheManager(redissonClient, config, JsonJacksonCodec.INSTANCE); |
| | | } |
| | | |
| | | @Bean |
| | | public DefaultRedisScript<Long> limitScript() |
| | | { |
| | | DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(); |
| | | redisScript.setScriptText(limitScriptText()); |
| | | redisScript.setResultType(Long.class); |
| | | return redisScript; |
| | | } |
| | | |
| | | /** |
| | | * 限流脚本 |
| | | */ |
| | | private String limitScriptText() |
| | | { |
| | | return "local key = KEYS[1]\n" + |
| | | "local count = tonumber(ARGV[1])\n" + |
| | | "local time = tonumber(ARGV[2])\n" + |
| | | "local current = redis.call('get', key);\n" + |
| | | "if current and tonumber(current) > count then\n" + |
| | | " return current;\n" + |
| | | "end\n" + |
| | | "current = redis.call('incr', key)\n" + |
| | | "if tonumber(current) == 1 then\n" + |
| | | " redis.call('expire', key, time)\n" + |
| | | "end\n" + |
| | | "return current;"; |
| | | } |
| | | |
| | | } |