https://blog.csdn.net/qq_33762302/article/details/116258617
1 import java.lang.annotation.*;
2
3 @Target(ElementType.METHOD)
4 @Retention(RetentionPolicy.RUNTIME)
5 @Documented
6 public @interface IpLimiter {
7 /**
8 * 放行ip
9 */
10 String[] ipAdress() default {""};
11 /**
12 * 单位时间限制通过请求数
13 */
14 long limit() default 10;
15 /**
16 * 单位时间,单位秒
17 */
18 long time() default 1;
19 /**
20 * 达到限流提示语
21 */
22 String message();
23
24 /**
25 * 是否锁住IP的同时锁住URI
26 */
27 boolean lockUri() default false;
28 }
IpLimterHandler.java 注解AOP处理。
1 import com.missionex.common.annotation.IpLimiter;
2 import com.missionex.common.core.domain.AjaxResult;
3 import com.missionex.common.utils.DateUtils;
4 import com.missionex.common.utils.SecurityUtils;
5 import com.missionex.common.utils.http.IPAddressUtils;
6 import org.aspectj.lang.ProceedingJoinPoint;
7 import org.aspectj.lang.Signature;
8 import org.aspectj.lang.annotation.Around;
9 import org.aspectj.lang.annotation.Aspect;
10 import org.aspectj.lang.reflect.MethodSignature;
11 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory;
13 import org.springframework.beans.factory.annotation.Autowired;
14 import org.springframework.core.io.ClassPathResource;
15 import org.springframework.data.redis.core.StringRedisTemplate;
16 import org.springframework.data.redis.core.script.DefaultRedisScript;
17 import org.springframework.scripting.support.ResourceScriptSource;
18 import org.springframework.stereotype.Component;
19 import org.springframework.web.context.request.RequestContextHolder;
20 import org.springframework.web.context.request.ServletRequestAttributes;
21
22 import javax.annotation.PostConstruct;
23 import javax.servlet.http.HttpServletRequest;
24 import java.util.ArrayList;
25 import java.util.List;
26
27 @Aspect
28 @Component
29 public class IpLimterHandler {
30
31 private static final Logger LOGGER = LoggerFactory.getLogger("request-limit");
32
33 @Autowired
34 StringRedisTemplate redisTemplate;
35
36
37 /**
38 * getRedisScript 读取脚本工具类
39 * 这里设置为Long,是因为ipLimiter.lua 脚本返回的是数字类型
40 */
41 private DefaultRedisScript<Long> getRedisScript;
42
43 @PostConstruct
44 public void init() {
45 getRedisScript = new DefaultRedisScript<>();
46 getRedisScript.setResultType(Long.class);
47 getRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("ipLimiter.lua")));
48 LOGGER.info("IpLimterHandler[分布式限流处理器]脚本加载完成");
49 }
50
51 /**
52 * 这个切点可以不要,因为下面的本身就是个注解
53 */
54 // @Pointcut("@annotation(com.jincou.iplimiter.annotation.IpLimiter)")
55 // public void rateLimiter() {}
56
57 /**
58 * 如果保留上面这个切点,那么这里可以写成
59 * @Around("rateLimiter()&&@annotation(ipLimiter)")
60 */
61 @Around("@annotation(ipLimiter)")
62 public Object around(ProceedingJoinPoint proceedingJoinPoint, IpLimiter ipLimiter) throws Throwable {
63 if (LOGGER.isDebugEnabled()) {
64 LOGGER.debug("IpLimterHandler[分布式限流处理器]开始执行限流操作");
65 }
66 String userIp = null;
67 String requestURI = null;
68 try {
69 // 获取请求信息
70 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
71 requestURI = request.getRequestURI();
72 String requestMethod = request.getMethod();
73 String remoteAddr = request.getRemoteAddr();
74 // 获取请求用户IP
75 userIp = IPAddressUtils.getIpAdrress(request);
76 if (userIp == null) {
77 return AjaxResult.error("运行环境存在风险");
78 }
79 } catch (Exception e) {
80 LOGGER.error("获取request出错=>" + e.getMessage());
81 if (userIp == null) {
82 return AjaxResult.error("运行环境存在风险");
83 }
84 }
85 Signature signature = proceedingJoinPoint.getSignature();
86 if (!(signature instanceof MethodSignature)) {
87 throw new IllegalArgumentException("the Annotation @IpLimter must used on method!");
88 }
89 /**
90 * 获取注解参数
91 */
92 // 放行模块IP
93 String[] limitIp = ipLimiter.ipAdress();
94 int len;
95 if (limitIp != null && (len = limitIp.length) != 0) {
96 for (int i = 0; i < len; i++) {
97 if (limitIp[i].equals(userIp)) {
98 return proceedingJoinPoint.proceed();
99 }
100 }
101 }
102 // 限流阈值
103 long limitTimes = ipLimiter.limit();
104 // 限流超时时间
105 long expireTime = ipLimiter.time();
106 boolean lockUri = ipLimiter.lockUri();
107 if (LOGGER.isDebugEnabled()) {
108 LOGGER.debug("IpLimterHandler[分布式限流处理器]参数值为-limitTimes={},limitTimeout={}", limitTimes, expireTime);
109 }
110 // 限流提示语
111 String message = ipLimiter.message();
112 /**
113 * 执行Lua脚本
114 */
115 List<String> ipList = new ArrayList();
116 // 设置key值为注解中的值
117 if (lockUri) {
118 ipList.add(userIp+requestURI);
119 } else {
120 ipList.add(userIp);
121 }
122 /**
123 * 调用脚本并执行
124 */
125 try {
126 Object x = redisTemplate.execute(getRedisScript, ipList, expireTime+"", limitTimes+"");
127 Long result = (Long) x;
128 if (result == 0) {
129 Long userId = null;
130 try {
131 userId = SecurityUtils.getLoginUser().getAppUser().getId();
132 } catch (Exception e) {
133
134 }
135 LOGGER.info("[分布式限流处理器]限流执行结果-ip={}-接口={}-用户ID={}-result={}-time={},已被限流", userIp,requestURI == null?"未知":requestURI
136 ,userId==null?"用户未登录":userId,result, DateUtils.getTime());
137 // 达到限流返回给前端信息
138 return AjaxResult.error(message);
139 }
140 if (LOGGER.isDebugEnabled()) {
141 LOGGER.debug("IpLimterHandler[分布式限流处理器]限流执行结果-result={},请求[正常]响应", result);
142 }
143 return proceedingJoinPoint.proceed();
144 } catch (Exception e) {
145 LOGGER.error("限流错误",e);
146 return proceedingJoinPoint.proceed();
147 }
148
149 }
150 }
ipLimiter.lua 脚本,放在resources文件夹中。
1 -获取KEY
2 local key1 = KEYS[1]
3
4 local val = redis.call('incr', key1)
5 local ttl = redis.call('ttl', key1)
6
7 --获取ARGV内的参数并打印
8 local expire = ARGV[1]
9 local times = ARGV[2]
10
11 redis.log(redis.LOG_DEBUG,tostring(times))
12 redis.log(redis.LOG_DEBUG,tostring(expire))
13
14 redis.log(redis.LOG_NOTICE, "incr "..key1.." "..val);
15 if val == 1 then
16 redis.call('expire', key1, tonumber(expire))
17 else
18 if ttl == -1 then
19 redis.call('expire', key1, tonumber(expire))
20 end
21 end
22
23 if val > tonumber(times) then
24 return 0
25 end
26 return 1
RedisConfig.java redis配置(该配置继承了CachingConfigurerSupport)中对写入redis的数据的序列化。
如果使用IP锁的时候,错误出现在了AOP中的使用脚本写入redis的时候(像什么Long无法转String的错误),基本是这边序列化没配好。
1 @Bean
2 @SuppressWarnings(value = { "unchecked", "rawtypes" })
3 public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
4 {
5 RedisTemplate<Object, Object> template = new RedisTemplate<>();
6 template.setConnectionFactory(connectionFactory);
7 FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
8 // 使用StringRedisSerializer来序列化和反序列化redis的key值
9 template.setKeySerializer(new StringRedisSerializer());
10 template.setValueSerializer(serializer);
11 // Hash的key也采用StringRedisSerializer的序列化方式
12 template.setHashKeySerializer(new StringRedisSerializer());
13 template.setHashValueSerializer(serializer);
14 template.afterPropertiesSet();
15 return template;
16 }
使用示范。
1 @PostMapping("/test")
2 @IpLimiter(limit = 2, time = 5, message = "您访问过于频繁,请稍候访问",lockUri = true)
3 public AjaxResult test(@RequestBody Map map){
4 //代码......
5 }
我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden
我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge
华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o
C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.
MIMO技术的优缺点优点通过下面三个增益来总体概括:阵列增益。阵列增益是指由于接收机通过对接收信号的相干合并而活得的平均SNR的提高。在发射机不知道信道信息的情况下,MIMO系统可以获得的阵列增益与接收天线数成正比复用增益。在采用空间复用方案的MIMO系统中,可以获得复用增益,即信道容量成倍增加。信道容量的增加与min(Nt,Nr)成正比分集增益。在采用空间分集方案的MIMO系统中,可以获得分集增益,即可靠性性能的改善。分集增益用独立衰落支路数来描述,即分集指数。在使用了空时编码的MIMO系统中,由于接收天线或发射天线之间的间距较远,可认为它们各自的大尺度衰落是相互独立的,因此分布式MIMO
遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg
通常,数组被实现为内存块,集合被实现为HashMap,有序集合被实现为跳跃列表。在Ruby中也是如此吗?我正在尝试从性能和内存占用方面评估Ruby中不同容器的使用情况 最佳答案 数组是Ruby核心库的一部分。每个Ruby实现都有自己的数组实现。Ruby语言规范只规定了Ruby数组的行为,并没有规定任何特定的实现策略。它甚至没有指定任何会强制或至少建议特定实现策略的性能约束。然而,大多数Rubyist对数组的性能特征有一些期望,这会迫使不符合它们的实现变得默默无闻,因为实际上没有人会使用它:插入、前置或追加以及删除元素的最坏情况步骤复
在ruby中,你可以这样做:classThingpublicdeff1puts"f1"endprivatedeff2puts"f2"endpublicdeff3puts"f3"endprivatedeff4puts"f4"endend现在f1和f3是公共(public)的,f2和f4是私有(private)的。内部发生了什么,允许您调用一个类方法,然后更改方法定义?我怎样才能实现相同的功能(表面上是创建我自己的java之类的注释)例如...classThingfundeff1puts"hey"endnotfundeff2puts"hey"endendfun和notfun将更改以下函数定
我目前有一个reddit克隆类型的网站。我正在尝试根据我的用户之前喜欢的帖子推荐帖子。看起来K最近邻或k均值是执行此操作的最佳方法。我似乎无法理解如何实际实现它。我看过一些数学公式(例如k表示维基百科页面),但它们对我来说并没有真正意义。有人可以推荐一些伪代码,或者可以查看的地方,以便我更好地了解如何执行此操作吗? 最佳答案 K最近邻(又名KNN)是一种分类算法。基本上,您采用包含N个项目的训练组并对它们进行分类。如何对它们进行分类完全取决于您的数据,以及您认为该数据的重要分类特征是什么。在您的示例中,这可能是帖子类别、谁发布了该项
我想在Ruby的TCPServer中获取客户端的IP地址。以及(如果可能的话)MAC地址。例如,Ruby中的时间服务器,请参阅评论。tcpserver=TCPServer.new("",80)iftcpserverputs"Listening"loopdosocket=tcpserver.acceptifsocketThread.newdoputs"Connectedfrom"+#HERE!HowcanigettheIPAddressfromtheclient?socket.write(Time.now.to_s)socket.closeendendendend非常感谢!