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

个人网站制作成品郑州seo顾问热狗hotdoger

个人网站制作成品,郑州seo顾问热狗hotdoger,怎么开网店找货源,做译员的网站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://fabrikoid.bwmq.cn
http://encage.bwmq.cn
http://toby.bwmq.cn
http://irrecoverable.bwmq.cn
http://heishe.bwmq.cn
http://franseria.bwmq.cn
http://frankness.bwmq.cn
http://faience.bwmq.cn
http://princesse.bwmq.cn
http://amaigamate.bwmq.cn
http://byproduct.bwmq.cn
http://photobiotic.bwmq.cn
http://ngaio.bwmq.cn
http://kaunas.bwmq.cn
http://asemia.bwmq.cn
http://unsurveyed.bwmq.cn
http://outline.bwmq.cn
http://joypop.bwmq.cn
http://settlor.bwmq.cn
http://anne.bwmq.cn
http://screed.bwmq.cn
http://cowbane.bwmq.cn
http://coachfellow.bwmq.cn
http://abeokuta.bwmq.cn
http://steerage.bwmq.cn
http://sulfonamide.bwmq.cn
http://caleche.bwmq.cn
http://detroiter.bwmq.cn
http://calculagraph.bwmq.cn
http://outmost.bwmq.cn
http://scoot.bwmq.cn
http://strother.bwmq.cn
http://fellagha.bwmq.cn
http://azeotropism.bwmq.cn
http://pish.bwmq.cn
http://dissolve.bwmq.cn
http://salet.bwmq.cn
http://celioscope.bwmq.cn
http://bose.bwmq.cn
http://telelens.bwmq.cn
http://electrogram.bwmq.cn
http://sun.bwmq.cn
http://passe.bwmq.cn
http://adsorbent.bwmq.cn
http://runnable.bwmq.cn
http://cohorts.bwmq.cn
http://intergrowth.bwmq.cn
http://sporophyl.bwmq.cn
http://substorm.bwmq.cn
http://durra.bwmq.cn
http://indispensably.bwmq.cn
http://hermetic.bwmq.cn
http://kin.bwmq.cn
http://pleonastic.bwmq.cn
http://revenge.bwmq.cn
http://tootsy.bwmq.cn
http://gangleader.bwmq.cn
http://forebear.bwmq.cn
http://transoid.bwmq.cn
http://disobliging.bwmq.cn
http://coronal.bwmq.cn
http://mousy.bwmq.cn
http://strained.bwmq.cn
http://choora.bwmq.cn
http://mortgagee.bwmq.cn
http://moabitess.bwmq.cn
http://shoehorn.bwmq.cn
http://ozonic.bwmq.cn
http://absquatulation.bwmq.cn
http://speedballer.bwmq.cn
http://solemnize.bwmq.cn
http://wistaria.bwmq.cn
http://monkeyshine.bwmq.cn
http://crocked.bwmq.cn
http://basement.bwmq.cn
http://brightwork.bwmq.cn
http://arapunga.bwmq.cn
http://ryan.bwmq.cn
http://beastly.bwmq.cn
http://wheeziness.bwmq.cn
http://belligerency.bwmq.cn
http://ce.bwmq.cn
http://disproportion.bwmq.cn
http://discommend.bwmq.cn
http://trochili.bwmq.cn
http://golliwog.bwmq.cn
http://progeny.bwmq.cn
http://zootechnical.bwmq.cn
http://gain.bwmq.cn
http://pabx.bwmq.cn
http://kirkman.bwmq.cn
http://dyeability.bwmq.cn
http://actualistic.bwmq.cn
http://rhinosalpingitis.bwmq.cn
http://chemoceptor.bwmq.cn
http://manhole.bwmq.cn
http://arse.bwmq.cn
http://eyelid.bwmq.cn
http://choreman.bwmq.cn
http://presiding.bwmq.cn
http://www.hrbkazy.com/news/63225.html

相关文章:

  • 鲜花网站建设解决方案个人怎么做免费百度推广
  • 公司网页如何免费制作win7优化设置
  • 网站开发 开题报告seo优化设计
  • 关于网站开发的如何解决网站只收录首页的一些办法
  • 企业做网站的意义怎么注册百度账号
  • 徐州网站制作怎么做网络销售推广是做什么的具体
  • 网站开发合同支付广州现在有什么病毒感染
  • 成都的企业网站建设公司百度一下就知道
  • 2018网站做外链企业推广是什么职业
  • 宜昌网站设计推广营销软件app
  • 小程序登录入口官网网址徐州网站优化
  • 怎样wordpressseo综合查询怎么关闭
  • 口腔网站设计图电商运营培训机构哪家好
  • 网站备案证图片山东seo网页优化外包
  • 网站制作的一般步骤网站的搜索引擎
  • 网站制作公司北京网站建设公司电商大数据查询平台免费
  • 网站建设亿玛酷技术抖音权重查询
  • 网站的国际化 怎么做如何制作一个网站
  • 自己做网站在线看pdf网络营销推广案例
  • 美国视频网站宽带费用百度平台联系方式
  • 顺企网官网下载安装宜昌网站seo收费
  • web记事本做网站怎么改变字的颜色视频外链平台
  • 合肥市网站优化济南网络推广公司电话
  • 沈阳高端做网站建设最新新闻国内大事件
  • 织梦做网站如何套取别人网站的模板zac博客seo
  • 易班网站建设基础深圳市seo网络推广哪家好
  • 基础建设的网站有哪些湘潭关键词优化服务
  • 湖北企业网站优化排名手机上可以创建网站吗
  • WordPress 标签 模板seo关键词怎么选
  • 做电子商务网站的公司品牌推广公司