当前位置:网站首页>How can redis+aop customize annotations to achieve flow restriction
How can redis+aop customize annotations to achieve flow restriction
2022-06-30 02:46:00 【Yisu cloud】
Redis+AOP How to customize annotations to implement flow restriction
Today I'd like to share with you Redis+AOP How to customize annotations to realize flow restriction , Detailed content , Clear logic , I believe most people still know too much about this knowledge , So share this article for your reference , I hope you will gain something after reading this article , Now let's take a look .
download
1, The download page
2, download
decompression
tar -xzvf redis-5.0.7.tar.gz
Prepare to compile
1, 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=libc
make 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 test
If you see the following words : No mistakes :\o/ All tests passed without errors!
install
[[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.conf
Set the following two places :
# daemonize no daemonize yes # maxmemory <bytes>maxmemory 128MB
explain : 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.service
2,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.target
3. Overloading system services
[[email protected] liuhongdi]# systemctl daemon-reload
4, 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 redis
1、 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 : to open up The server Port number , 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 limiting
On 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: 123456
3、 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 How to customize annotations to implement flow restriction ” All the content of this article , Thank you for reading ! I believe you will gain a lot after reading this article , Xiaobian will update different knowledge for you every day , If you want to learn more , Please pay attention to the Yisu cloud industry information channel .
边栏推荐
- Shenzhen CPDA Data Analyst Certification in July 2022
- Global and Chinese markets for light cargo conveyors 2022-2028: Research Report on technology, participants, trends, market size and share
- Some configuration details about servlet initial development
- 什么是自签名证书?自签名SSL证书的优缺点?
- (graph theory) connected component (template) + strongly connected component (template)
- FAQs for code signature and driver signature
- Call collections Sort() method, compare two person objects (by age ratio first, and by name ratio for the same age), and pass lambda expression as a parameter.
- Jupyter notebook显示k线图集合
- CMake教程系列-04-编译相关函数
- Implementation of Sanzi chess with C language
猜你喜欢

打造创客教育中精湛技艺

FDA ESG regulation: digital certificate must be used to ensure communication security

Summary of knowledge points about eigenvalues and eigenvectors of matrices in Chapter 5 of Linear Algebra (Jeff's self perception)

FDA ESG规定:必须使用数字证书保证通信安全

HTA入门基础教程 | VBS脚本的GUI界面 HTA简明教程 ,附带完整历程及界面美化

A quick look at the statistical data of 23 major cyber crimes from 2021 to 2022

Créer des compétences exquises dans l'éducation des créateurs

怎么利用Redis实现点赞功能

LeetCode 3. 无重复字符的最长子串

Select sort
随机推荐
CMake教程系列-01-最小配置示例
Raki's notes on reading paper: neighborhood matching network for entity alignment
福利抽奖 | 开源企业级监控Zabbix6.0都有哪些亮点
Multi card server usage
Jupyter notebook displays a collection of K-line graphs
Sitelock nine FAQs
2022 the action of protecting the net is imminent. Things about protecting the net
怎么使用Vant实现数据分页和下拉加载
隐藏在科技教育中的steam元素
Template parameter package and function parameter package
什么是证书透明度CT?如何查询CT logs证书日志?
SSL证书七大常见错误及解决方法
在php中字符串的概念是什么
代码签名、驱动签名的常见问题解答
FAQs for code signature and driver signature
What is the difference between a layer 3 switch and a layer 2 switch
uniapp 地址转换经纬度
FDA邮件安全解决方案
2.< tag-动态规划和0-1背包问题>lt.416. 分割等和子集 + lt.1049. 最后一块石头的重量 II
Global and Chinese markets of liquid optical waveguides 2022-2028: Research Report on technology, participants, trends, market size and share