当前位置:网站首页>Redis+aop+ user defined annotation to realize flow restriction
Redis+aop+ user defined annotation to realize flow restriction
2022-06-28 22:28:00 【1024 Q】
Redis install
download
decompression
Prepare to compile
compile
Test compilation
install
To configure
function
Check whether the port is in use
see redis The current version of :
send redis It can be used systemd Way to start and manage
View local centos Version of :
Client connection redis
Redis Current limiting
1、 Introduce dependencies
2、application.yml To configure
3、 establish redisConfig, introduce redisTemplate
Custom annotations and interceptors
1、 Custom annotation
2、 Create interceptor
3、 Add a custom interceptor to the interceptor list
Redis installAt the mention of Redis, I believe everyone will not feel strange . Today, let's install on Alibaba cloud Redis, Prepare for future use .
download1, The download page
2, download
decompressiontar -xzvf redis-5.0.7.tar.gz
Prepare to compile1, Please confirm before operation gcc Installed or not ,gcc -v
If not installed , You can execute this command to install :yum install gcc
2, Please confirm before operation tcl Whether it has been installed if not , You can execute this command to install :yum install tcl
compile[[email protected] source]# cd redis-5.0.7/[[email protected] redis-5.0.7]# make MALLOC=libcmake After add MALLOC The reason for the parameter :
Avoid prompting not to find jemalloc/jemalloc.h
Test compilation[[email protected] redis-5.0.7]# make testIf you see the following words : No mistakes :\o/ All tests passed without errors!
install[root[email protected] redis-5.0.7]# mkdir /usr/local/soft/redis5 Can be created step by step [[email protected] redis-5.0.7]# cd /usr/local/soft/redis5/[[email protected] redis5]# mkdir bin[[email protected] redis5]# mkdir conf[[email protected] redis5]# cd bin/find / -name redis-cli Find file location
[[email protected] bin]# cp /root/redis-5.0.7/src/redis-cli ./[[email protected] bin]# cp /root/redis-5.0.7/src/redis-server ./[[email protected] bin]# cd …/conf/[[email protected] conf]# cp /root/redis-5.0.7/redis.conf ./ To configure [[email protected] conf]# vi redis.confSet the following two places :
# daemonize no daemonize yes # maxmemory <bytes>maxmemory 128MBexplain : The difference is that daemon Mode operates independently / Maximum memory usage limit
function[[email protected] conf]# /usr/local/soft/redis5/bin/redis-server /usr/local/soft/redis5/conf/redis.conf Check whether the port is in use [[email protected] conf]# netstat -anp | grep 6379tcp 0 0 127.0.0.1:6379 0.0.0.0:* LISTEN 16073/redis-server see redis The current version of :[[email protected] conf]# /usr/local/soft/redis5/bin/redis-server -vRedis server v=5.0.7 sha=00000000:0 malloc=libc bits=64 build=8e31d2ed9a4c9593 send redis It can be used systemd Way to start and manage 1, edit service file
[[email protected] liuhongdi]# vim /lib/systemd/system/redis.service2,service The contents of the document :
[Unit]Description=RedisAfter=network.target[Service]Type=forkingPIDFile=/var/run/redis_6379.pidExecStart=/usr/local/soft/redis5/bin/redis-server /usr/local/soft/redis5/conf/redis.confExecReload=/bin/kill -s HUP $MAINPIDExecStop=/bin/kill -s QUIT $MAINPIDPrivateTmp=true[Install]WantedBy=multi-user.target3. Overloading system services
[[email protected] liuhongdi]# systemctl daemon-reload4, Used to manage redis
start-up
systemctl start redis
Check the status
systemctl status redis
Make the machine start
systemctl enable redis
View local centos Version of :[[email protected] lib]# cat /etc/redhat-releaseCentOS Linux release 8.1.1911 (Core) Client connection redis1、 Alibaba cloud has to set redis.conf Medium bind Followed by 127.0.0.1 It is amended as follows 0.0.0.0, restart redis
2、 Open ports : Port number of the open server , Steps are as follows :
Open the instance list , Click on “ more ” Button , choice “ Network and security groups ” Medium “ Security group configuration ”, choice “ Security group list ”tab page , Click on “ Configuration rules ” Button , Click on “ Quick add ” Button , Check “Redis(6379)”, Click on “ determine ” Then you can connect normally .
3、 to redis Set the connection password :
Find the # requirepass foobared Remove the comment and write the password to be set , for example :requirepass 123456
redis Test whether the command can be connected after startup
./redis-cli -h 127.0.0.1 -p 6379127.0.0.1:6379> auth 123456// Here is your password Be careful : If it is Alibaba cloud, you must set the password , Otherwise, it may be injected into the scheduled task by the miner program , Mine with your server , Alibaba cloud always has information to remind you .
Redis Current limitingOn the server Redis The installation is complete ( See above for installation steps ), Today let's use Redis To do a little function : Custom interceptors limit access times , That is, current limiting .
First, we need to introduce Redis
1、 Introduce dependencies<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency><!-- redis rely on commons-pool This dependency must add --><dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId></dependency>2、application.yml To configure server:port: 8181spring:redis: host: 127.0.0.1 port: 6379 timeout: 10s lettuce: pool: # The smallest free connection in the connection pool Default 0 min-idle: 0 # The maximum free connection in the connection pool Default 8 max-idle: 8 # Maximum number of connections in connection pool Default 8 , A negative number means there is no limit max-active: 8 # Connection pool maximum blocking wait time ( Use a negative value to indicate that there is no limit ) Default -1 max-wait: -1ms # Select which inventory to store , The default is 0 database: 0 password: 1234563、 establish redisConfig, introduce redisTemplate@Configurationpublic class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setConnectionFactory(redisConnectionFactory); return redisTemplate; }} Custom annotations and interceptors 1、 Custom annotation @Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@Documentedpublic @interface AccessLimit { int seconds(); // Number of seconds int maxCount(); // Maximum number of visits boolean needLogin()default true;// Do you need to log in }2、 Create interceptor @Componentpublic class FangshuaInterceptor extends HandlerInterceptorAdapter { @Autowired private RedisTemplate redisTemplate; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // Determine whether the request belongs to the method's request if(handler instanceof HandlerMethod){ HandlerMethod hm = (HandlerMethod) handler; // Gets the annotations in the method , See if there's a comment AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class); if(accessLimit == null){ return true; } int seconds = accessLimit.seconds(); int maxCount = accessLimit.maxCount(); boolean login = accessLimit.needLogin(); String key = request.getRequestURI(); // If you need to log in if(login){ // Get logged in session Judge , This is just an example , Do not write specific business //..... key+=""+"1"; // Let's assume that the user is 1, The project is dynamically captured userId } // from redis Get the number of user visits Integer count; if(Objects.isNull(redisTemplate.opsForValue().get(key))){ count = 0; }else{ count = (Integer) redisTemplate.opsForValue().get(key); } if(count == 0){ redisTemplate.opsForValue().set(key,1,seconds, TimeUnit.SECONDS); }else if(count<maxCount){ //key The value of the add 1 redisTemplate.opsForValue().increment(key); }else{ // More visits Map<String,Object> errMap=new HashMap<>(); errMap.put("code",400); errMap.put("msg"," request timeout , Please try again later "); render(response,errMap); // there CodeMsg Is a return parameter return false; } } return true; } private void render(HttpServletResponse response, Map<String,Object> errMap) throws Exception { response.setContentType("application/json;charset=UTF-8"); OutputStream out = response.getOutputStream(); String str = JSON.toJSONString(errMap); out.write(str.getBytes("UTF-8")); out.flush(); out.close(); }}3、 Add a custom interceptor to the interceptor list @Configurationpublic class WebConfig extends WebMvcConfigurerAdapter { @Autowired private FangshuaInterceptor interceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(interceptor); }}Finally, do a simple test
@[email protected]("test")public class TestController { // You can request up to three times every thirty seconds , You don't need to log in @AccessLimit(seconds=30, maxCount=3, needLogin=false) @PostMapping("/fangshua") public String fangshua(){ return " success "; }}That's all Redis+AOP+ The user-defined annotation implements the details of flow restriction , More about Redis For current limiting information, please pay attention to other relevant articles on the software development network !
边栏推荐
- IC Nansha|AMD高级副总裁、大中华区总裁潘晓明:制程、架构、平台优化突破计算边界
- 利用Redis实现点赞功能的示例代码
- 【HackTheBox】dancing(SMB)
- Gross vs60 billion. Is food safety the biggest obstacle to Weilong's listing?
- 【SSH】无密码登录
- Oracle删除归档日志及添加定时任务
- 如何制作精美的图片
- Dart的类扩展、可选类型扩展
- What is the prospect of VR panoramic production?
- In the era of industrial Internet, the Internet in the traditional sense will evolve into many new forms
猜你喜欢

Zadig + cave Iast: let safety dissolve in continuous delivery

Ingénieur natif du nuage après 00: utiliser Zadig pour développer des sources ouvertes et des économies d'énergie pour la technologie innovante (bus de Guangzhou)

VR全景制作的前景如何?

穿越过后,她说多元宇宙真的存在

分享im即时通讯开发之WebSocket:概念、原理、易错常识

Zadig + sonarqube, ensuring the safety of the development process

穿越过后,她说多元宇宙真的存在

The love digital smart 2022 summit opens, sharing data strategy and building data-driven organization methodology

初识阿里云(云计算)—发展历程和技术架构、地域和可用区!

How to make beautiful pictures
随机推荐
6年心得,从功能测试到测试开发,送给在测试路上一路走到黑的你
Use of axurer9 master
共探数字技术与信息安全,第四届中俄数字论坛成功举办
Career consultation | what should I answer when I am asked about my intended salary during the interview?
数据库基础笔记
穿越过后,她说多元宇宙真的存在
5毛VS600亿,食品安全问题是卫龙上市最大的拦路虎?
What is the prospect of VR panoramic production?
After crossing, she said that the multiverse really exists
Hardware development notes (VII): basic process of hardware development, making a USB to RS232 module (VI): creating 0603 package and associating principle graphic devices
Ansible production environment usage scenario (7): batch deployment of elk clients
现在还能入“坑”数据分析吗?看看2022年数据分析热门岗位!
Career consultation | how to answer the question of career planning during the interview?
计数排序的简单理解
How to advance data analysis from 1 to 10?
Gross vs60 billion. Is food safety the biggest obstacle to Weilong's listing?
What does project management really manage?
In the era of industrial Internet, the Internet in the traditional sense will evolve into many new forms
分享im即时通讯开发之WebSocket:概念、原理、易错常识
10、标准I/O输入输出重定向及管道