当前位置:网站首页>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 .
边栏推荐
- c#控制台格式化代码
- Playful palette: an interactive parametric color mixer for artists
- 三层交换机和二层交换机区别是什么
- 2022年7月深圳地区CPDA数据分析师认证
- FDA邮件安全解决方案
- Entering Jiangsu writers and poets carmine Jasmine World Book Day
- Global and Chinese markets for light cargo conveyors 2022-2028: Research Report on technology, participants, trends, market size and share
- Raki's notes on reading paper: discontinuous named entity recognition as maximum clique discovery
- 学术汇报(academic presentation)/PPT应该怎么做?
- 【干货分享】最新WHQL徽标认证申请流程
猜你喜欢

Recursion frog jumping steps problem

IBM websphere通道联通搭建和测试

Cmake tutorial series -02- generating binaries using cmake code

Bubble sort

什么是X.509证书?X.509证书工作原理及应用?

Unity TimeLine 数据绑定

Intel-Hex , Motorola S-Record 格式详细解析

打造创客教育中精湛技艺

Ffmpeg source code

A quick look at the statistical data of 23 major cyber crimes from 2021 to 2022
随机推荐
Cmake tutorial series -04- compiling related functions
微信小程序页面跳转以及参数传递
什么是自签名证书?自签名SSL证书的优缺点?
CMake教程系列-05-选项及变量
What is digicert smart seal?
Merge sort
What are the three paradigms of database
SiteLock九个常见问题
What is the difference between a layer 3 switch and a layer 2 switch
怎样的外汇交易平台是有监管的,是安全的?
Multi card server usage
Implementation of Sanzi chess with C language
Global and Chinese market of relay lens 2022-2028: Research Report on technology, participants, trends, market size and share
迅为恩智浦iTOP-IMX6开发平台
CA数字证书包含哪些文件?如何查看SSL证书信息?
Network neuroscience——网络神经科学综述
隐藏在科技教育中的steam元素
[dry goods sharing] the latest WHQL logo certification application process
Unity3D UGUI强制刷新Layout(布局)组件
IBM websphere通道联通搭建和测试