当前位置:网站首页>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 .
边栏推荐
猜你喜欢

重看《Redis设计与实现》后记录几个要点

福利抽奖 | 开源企业级监控Zabbix6.0都有哪些亮点

Software testing skills, JMeter stress testing tutorial, transaction controller of logic controller (25)

Seven common errors of SSL certificate and their solutions

Detailed explanation of minimum stack

Three solutions to forced hibernation of corporate computers

Unity3D UGUI强制刷新Layout(布局)组件

Five cheapest wildcard SSL certificate brands

What is digicert smart seal?

What should academic presentation /ppt do?
随机推荐
SSL证书格式转化的两种方法
How vscode debugs into standard library files / third-party package source code
Welfare lottery | what are the highlights of open source enterprise monitoring zabbix6.0
[Postgres] Postgres database migration
怎么使用Vant实现数据分页和下拉加载
Raii memory management
RAII内存管理
IBM websphere通道联通搭建和测试
Seven common errors of SSL certificate and their solutions
Network neuroscience——网络神经科学综述
A quick look at the statistical data of 23 major cyber crimes from 2021 to 2022
Merge sort
Sitelock nine FAQs
Pytorch学习(二)
FDA ESG regulation: digital certificate must be used to ensure communication security
Network neuroscience -- a review of network Neuroscience
Xunwei NXP itop-imx6 development platform
IBM WebSphere channel connectivity setup and testing
Lua 基础知识
如何在 JupyterLab 中把 ipykernel 切换到不同的 conda 虚拟环境?