当前位置:网站首页>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 .
边栏推荐
- Matlab code running tutorial (how to run the downloaded code)
- How to prevent phishing emails? S/mime mail certificate
- SiteLock九个常见问题
- 学术汇报(academic presentation)/PPT应该怎么做?
- Playful palette: an interactive parametric color mixer for artists
- Cmake tutorial series-01-minimum configuration example
- Cmake tutorial series -04- compiling related functions
- 怎么使用Vant实现数据分页和下拉加载
- 论文回顾:Playful Palette: An Interactive Parametric Color Mixer for Artists
- Unity timeline data binding
猜你喜欢

Entering Jiangsu writers and poets carmine Jasmine World Book Day

论文回顾:Playful Palette: An Interactive Parametric Color Mixer for Artists

SiteLock九个常见问题

How to switch ipykernel to a different CONDA virtual environment in jupyterlab?

Welfare lottery | what are the highlights of open source enterprise monitoring zabbix6.0

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

Sitelock nine FAQs

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

打造創客教育中精湛技藝

Jupyter notebook显示k线图集合
随机推荐
代码签名、驱动签名的常见问题解答
C console format code
What is digicert smart seal?
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.
[Postgres] Postgres database migration
[dry goods sharing] the latest WHQL logo certification application process
Linear algebra Chapter 4 Summary of knowledge points of linear equations (Jeff's self perception)
Recursion frog jumping steps problem
Cmake tutorial series-03-dependency management
什么是证书透明度CT?如何查询CT logs证书日志?
迅為恩智浦iTOP-IMX6開發平臺
最小栈详解
Raki's notes on reading paper: Leveraging type descriptions for zero shot named entity recognition and classification
C语言 pivot_root的Invalid argument错误解决方案
Intel-Hex , Motorola S-Record 格式详细解析
如何预防钓鱼邮件?S/MIME邮件证书来支招
FDA ESG regulation: digital certificate must be used to ensure communication security
Pytorch学习(二)
Global and Chinese market of Kanban software 2022-2028: Research Report on technology, participants, trends, market size and share
What should academic presentation /ppt do?