当前位置: 首页 > news >正文

网站开发技术thinkphp商业网点建设中心网站

网站开发技术thinkphp,商业网点建设中心网站,QQ点钓鱼网站后怎么做,网站开发法律1、Redis实现限流方案的核心原理&#xff1a; redis实现限流的核心原理在于redis 的key 过期时间&#xff0c;当我们设置一个key到redis中时&#xff0c;会将key设置上过期时间&#xff0c;这里的实现是采用lua脚本来实现原子性的。2、准备 引入相关依赖 <dependency>…

1、Redis实现限流方案的核心原理:

redis实现限流的核心原理在于redis 的key 过期时间,当我们设置一个key到redis中时,会将key设置上过期时间,这里的实现是采用lua脚本来实现原子性的。

2、准备

  • 引入相关依赖
<dependency>
<groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.23</version>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><version>3.1.5</version>
</dependency>
<dependency><groupId>org.yaml</groupId><artifactId>snakeyaml</artifactId><version>2.2</version>
</dependency>
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId>
</dependency>
<dependency><groupId>com.google.protobuf</groupId><artifactId>protobuf-java</artifactId><version>3.25.1</version>
</dependency>
  • 添加redis配置信息
server:port: 6650nosql:redis:host: XXX.XXX.XXX.XXXport: 6379password:database: 0spring:cache:type: redisredis:host: ${nosql.redis.host}port: ${nosql.redis.port}password: ${nosql.redis.password}lettuce:pool:enabled: truemax-active: 8max-idle: 8min-idle: 0max-wait: 1000
  • 配置redis Conf
@Configuration
public class RedisConfig {/*** 序列化* jackson2JsonRedisSerializer** @param redisConnectionFactory 复述,连接工厂* @return {@link RedisTemplate}<{@link Object}, {@link Object}>*/@Beanpublic RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<Object, Object> template = new RedisTemplate<>();template.setConnectionFactory(redisConnectionFactory);Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(om);template.setKeySerializer(jackson2JsonRedisSerializer);template.setHashKeySerializer(jackson2JsonRedisSerializer);template.setValueSerializer(jackson2JsonRedisSerializer);template.setHashValueSerializer(jackson2JsonRedisSerializer);template.afterPropertiesSet();return template;}/*** 加载lua脚本* @return {@link DefaultRedisScript}<{@link Long}>*/@Beanpublic DefaultRedisScript<Long> limitScript() {DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("luaFile/rateLimit.lua")));redisScript.setResultType(Long.class);return redisScript;}}

3、限流实现

  1. 编写核心lua脚本
local key = KEYS[1]
-- 取出key对应的统计,判断统计是否比限制大,如果比限制大,直接返回当前值
local count = tonumber(ARGV[1])
local time = tonumber(ARGV[2])
local current = redis.call('get', key)
if current and tonumber(current) > count thenreturn tonumber(current)
end
--如果不比限制大,进行++,重新设置时间
current = redis.call('incr', key)
if tonumber(current) == 1 thenredis.call('expire', key, time)
end
return tonumber(current)
  1. 编写注解 limiter
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RateLimiter {/*** 限流key*/String key() default "rate_limit:";/*** 限流时间,单位秒*/int time() default 60;/*** 限流次数*/int count() default 100;/*** 限流类型*/LimitType limitType() default LimitType.DEFAULT;
}
  1. 增加注解类型
public enum LimitType {/*** 默认策略全局限流*/DEFAULT,/*** 根据请求者IP进行限流*/IP
}
  1. 添加IPUtils
@Slf4j
public class IpUtils {/**ip的长度值*/private static final int IP_LEN = 15;/** 使用代理时,多IP分隔符*/private static final String SPLIT_STR = ",";/*** 获取IP地址* <p>* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址*/public static String getIpAddr(HttpServletRequest request) {String ip = null;try {ip = request.getHeader("x-forwarded-for");if (StrUtil.isBlank(ip)) {ip = request.getHeader("Proxy-Client-IP");}if (StrUtil.isBlank(ip)) {ip = request.getHeader("WL-Proxy-Client-IP");}if (StrUtil.isBlank(ip)) {ip = request.getHeader("HTTP_CLIENT_IP");}if (StrUtil.isBlank(ip)) {ip = request.getHeader("HTTP_X_FORWARDED_FOR");}if (StrUtil.isBlank(ip)) {ip = request.getRemoteAddr();}} catch (Exception e) {log.error("IPUtils ERROR ", e);}//使用代理,则获取第一个IP地址if (!StrUtil.isBlank(ip) && ip.length() > IP_LEN) {if (ip.indexOf(SPLIT_STR) > 0) {ip = ip.substring(0, ip.indexOf(SPLIT_STR));}}return ip;}
}
  1. 核心处理类
@Aspect
@Component
@Slf4j
public class RateLimiterAspect {@Resourceprivate RedisTemplate<Object, Object> redisTemplate;@Resourceprivate RedisScript<Long> limitScript;@Before("@annotation(rateLimiter)")public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable {String key = rateLimiter.key();int time = rateLimiter.time();int count = rateLimiter.count();String combineKey = getCombineKey(rateLimiter, point);List<Object> keys = Collections.singletonList(combineKey);try {Long number = redisTemplate.execute(limitScript, keys, count, time);if (number == null || number.intValue() > count) {throw new ServiceException("访问过于频繁,请稍候再试");}log.info("限制请求'{}',当前请求'{}',缓存key'{}'", count, number.intValue(), key);} catch (ServiceException e) {throw e;} catch (Exception e) {throw new RuntimeException("服务器限流异常,请稍候再试");}}public String getCombineKey(RateLimiter rateLimiter, JoinPoint point) {StringBuilder stringBuilder = new StringBuilder(rateLimiter.key());if (rateLimiter.limitType() == LimitType.IP) {stringBuilder.append(IpUtils.getIpAddr(((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest())).append("-");}MethodSignature signature = (MethodSignature) point.getSignature();Method method = signature.getMethod();Class<?> targetClass = method.getDeclaringClass();stringBuilder.append(targetClass.getName()).append("-").append(method.getName());return stringBuilder.toString();}
}

到此,我们就可以利用注解,对请求方法进行限流了

http://www.yayakq.cn/news/799891/

相关文章:

  • 温州网站建设方案维护河南省建设厅网站师林峰
  • 看网红直播做爰的网站晋城做网站
  • 欧美网站建设排名鹤壁市做网站
  • 乐都区公司网站建设网页设计与制作教程电子版pdf
  • 网站空间指的是什么天津网站设计成功柚米
  • 婚恋网站模板手机网站在线咨询代码
  • 江西做网站公司青海省高等级公路建设管理局网站
  • 网站实用性wordpress简码插件
  • 像淘宝类别网站怎么做网站seo内容优化
  • 企业网站开发前台模块设计淘客网站做单品类
  • 找素材的网站响应式网站示例
  • 旅游政务网站建设方案wordpress的后台
  • 做网站是先做界面还是先做后台中化建工北京建设投资有限公司网站
  • 短视频推广平台有哪些seo技巧是什么意思
  • 网站建设放在哪个费用外贸网站建设的败笔
  • 黄石网站建设推荐高明网站建设报价
  • 嘉兴手机网站建设大兴模板网站建设
  • 公司做网站有什么好处外贸seo网站搭建
  • 江门市网站建设公司怎么自己做网站吓别人
  • 神级网页设计网站上海每44秒就有一人死于新冠
  • 做酒类网站广东建设信息网手机版
  • 沈阳沈河区网站建设手机品牌排行榜
  • 展示网站多少钱一个网站备案 多少钱
  • 做网站需要自备服务器吗wordpress漂浮广告插件
  • php网站发送邮件北京网站建设备案代理
  • 学做淘宝店的网站辽宁建设工程信息网开标流程
  • 微商城网站建设策划书小程序开发模板源码
  • 江西求做网站专业做淘宝网站推广
  • 福清网站建设专家邢台做企业网站
  • 网站后台模板怎样使用应用公园制作app免费吗