最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Redis+AOP+自定義注解實現(xiàn)限流

 更新時間:2022年06月28日 15:39:51   作者:阿Q  
這篇文章主要為大家詳細介紹了如何利用Redis+AOP+自定義注解實現(xiàn)個小功能:自定義攔截器限制訪問次數(shù),也就是限流,感興趣的可以了解一下

Redis安裝

一提到Redis,相信大家都不會感到陌生吧。今天就讓我們在阿里云上安裝一下Redis,為以后使用它做個準備。

下載

1,下載頁面

2,下載

解壓

tar -xzvf redis-5.0.7.tar.gz

準備編譯

1, 請在操作前確認gcc是否已安裝,gcc -v

如未安裝,可以執(zhí)行這個命令安裝:yum install gcc

2,請在操作前確認tcl是否已安裝如未安裝,可以執(zhí)行這個命令安裝:yum install tcl

編譯

[root@localhost source]# cd redis-5.0.7/
[root@localhost redis-5.0.7]# make MALLOC=libc

make 后加 MALLOC的參數(shù)的原因:

避免提示找不到 jemalloc/jemalloc.h

測試編譯

[root@localhost redis-5.0.7]# make test

如果看到以下字樣:表示無錯誤:\o/ All tests passed without errors!

安裝

[root@localhost redis-5.0.7]# mkdir /usr/local/soft/redis5 可分步創(chuàng)建
[root@localhost redis-5.0.7]# cd /usr/local/soft/redis5/
[root@localhost redis5]# mkdir bin
[root@localhost redis5]# mkdir conf
[root@localhost redis5]# cd bin/

find / -name redis-cli 查找文件位置

[root@localhost bin]# cp /root/redis-5.0.7/src/redis-cli ./
[root@localhost bin]# cp /root/redis-5.0.7/src/redis-server ./
[root@localhost bin]# cd …/conf/
[root@localhost conf]# cp /root/redis-5.0.7/redis.conf ./

配置

[root@localhost conf]# vi redis.conf

設(shè)置以下兩個地方:

# daemonize no 
 daemonize yes  
# maxmemory <bytes>
maxmemory 128MB

說明:分別是以daemon方式獨立運行 / 內(nèi)存的最大使用限制

運行

[root@localhost conf]# /usr/local/soft/redis5/bin/redis-server /usr/local/soft/redis5/conf/redis.conf

檢查端口是否在使用中

[root@localhost conf]# netstat -anp | grep 6379
???????tcp 0 0 127.0.0.1:6379 0.0.0.0:* LISTEN 16073/redis-server

查看redis的當前版本:

[root@localhost conf]# /usr/local/soft/redis5/bin/redis-server -v
???????Redis server v=5.0.7 sha=00000000:0 malloc=libc bits=64 build=8e31d2ed9a4c9593

使redis可以用systemd方式啟動和管理

1,編輯service文件

[root@localhost liuhongdi]# vim /lib/systemd/system/redis.service

2,service文件內(nèi)容:

[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.重載系統(tǒng)服務

[root@localhost liuhongdi]# systemctl daemon-reload

4,用來管理redis

啟動

systemctl start redis

查看狀態(tài)

systemctl status redis

使開機啟動

systemctl enable redis

查看本地centos的版本:

[root@localhost lib]# cat /etc/redhat-release
CentOS Linux release 8.1.1911 (Core)

客戶端連接redis

1、阿里云得設(shè)置redis.conf中的bind 后跟著的127.0.0.1修改為0.0.0.0,重啟redis

2、開放端口:開放服務器的端口號,步驟如下:

打開實例列表,點擊“ 更多”按鈕,選擇“ 網(wǎng)絡和安全組 ”中的“安全組配置”,選擇 “安全組列表”tab頁面,點擊 “配置規(guī)則”按鈕,點擊 “快速添加”按鈕,勾選“Redis(6379)”,點擊 “確定”之后就可以正常連接了。

3、給redis設(shè)置連接密碼:

查找到# requirepass foobared 注釋去掉并寫入要設(shè)置的密碼,例如:requirepass 123456

redis啟動之后測試是否可以連接命令

./redis-cli -h 127.0.0.1 -p 6379
127.0.0.1:6379> auth 123456//此處是你的密碼

注意: 如果是阿里云的話一定要設(shè)置密碼,否則很可能被礦機程序注入定時任務,用你的服務器挖礦,阿里云一直會有信息提示你。

Redis限流

服務器上的Redis已經(jīng)安裝完成了(安裝步驟見上文),今天就讓我們使用Redis來做個小功能:自定義攔截器限制訪問次數(shù),也就是限流。

首先我們要在項目中引入Redis

1、引入依賴

<dependency>
? <groupId>org.springframework.boot</groupId>
? <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- redis依賴commons-pool 這個依賴一定要添加 -->
<dependency>
? <groupId>org.apache.commons</groupId>
? <artifactId>commons-pool2</artifactId>
</dependency>

2、application.yml配置

server:
port: 8181

spring:
redis:
? host: 127.0.0.1
? port: 6379
? timeout: 10s
? lettuce:
? ? pool:
? ? # 連接池中的最小空閑連接 默認0
? ? ? min-idle: 0
? ? ? # 連接池中的最大空閑連接 默認8
? ? ? max-idle: 8
? ? ? # 連接池最大連接數(shù) 默認8 ,負數(shù)表示沒有限制
? ? ? max-active: 8
? ? ? # 連接池最大阻塞等待時間(使用負值表示沒有限制) 默認-1
? ? ? max-wait: -1ms
? #選擇哪個庫存儲,默認是0
? database: 0
? password: 123456

3、創(chuàng)建redisConfig,引入redisTemplate

@Configuration
public 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;
? }
}

自定義注解和攔截器

1、自定義注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface AccessLimit {
? ?int?seconds(); //秒數(shù)
? ?int?maxCount(); //最大訪問次數(shù)
? ?boolean?needLogin()default true;//是否需要登錄
}

2、創(chuàng)建攔截器

@Component
public class FangshuaInterceptor extends?HandlerInterceptorAdapter?{

? ?@Autowired
? ?private?RedisTemplate?redisTemplate;

? ?@Override
? ?public boolean?preHandle(HttpServletRequest?request,?HttpServletResponse?response, Object?handler) throws?Exception?{
? ? ? ?//判斷請求是否屬于方法的請求
? ? ? ?if(handler?instanceof?HandlerMethod){
? ? ? ? ? ?HandlerMethod?hm?=?(HandlerMethod)?handler;
? ? ? ? ? ?//獲取方法中的注解,看是否有該注解
? ? ? ? ? ?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(login){
? ? ? ? ? ? ? ?//獲取登錄的session進行判斷,此處只是例子,不寫具體的業(yè)務
? ? ? ? ? ? ? ?//.....
? ? ? ? ? ? ? ?key+=""+"1"; ?//這里假設(shè)用戶是1,項目中是動態(tài)獲取的userId
? ? ? ? ? }

? ? ? ? ? ?//從redis中獲取用戶訪問的次數(shù)
? ? ? ? ? ?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的值加1
? ? ? ? ? ? ? ?redisTemplate.opsForValue().increment(key);
? ? ? ? ? }else{
? ? ? ? ? ? ? ?//超出訪問次數(shù)
? ? ? ? ? ? ? ?Map<String,Object>?errMap=new?HashMap<>();
? ? ? ? ? ? ? ?errMap.put("code",400);
? ? ? ? ? ? ? ?errMap.put("msg","請求超時,請稍后再試");
? ? ? ? ? ? ? ?render(response,errMap); //這里的CodeMsg是一個返回參數(shù)
? ? ? ? ? ? ? ?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、將自定義攔截器加入到攔截器列表中

@Configuration
public class WebConfig extends?WebMvcConfigurerAdapter?{

? ?@Autowired
? ?private?FangshuaInterceptor?interceptor;

? ?@Override
? ?public void?addInterceptors(InterceptorRegistry?registry) {
? ? ? ?registry.addInterceptor(interceptor);
? }
}

最后做一下簡單的測試

@RestController
@RequestMapping("test")
public class TestController {

? ?//每三十秒最多可以請求三次,不需要登錄
? ?@AccessLimit(seconds=30,?maxCount=3,?needLogin=false)
? ?@PostMapping("/fangshua")
? ?public String?fangshua(){
? ? ? ?return "成功";
? }
}

以上就是Redis+AOP+自定義注解實現(xiàn)限流的詳細內(nèi)容,更多關(guān)于Redis限流的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Redis自動化安裝及集群實現(xiàn)搭建過程

    Redis自動化安裝及集群實現(xiàn)搭建過程

    這篇文章主要介紹了Redis自動化安裝以及集群實現(xiàn)搭建過程,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-09-09
  • k8s部署redis集群實現(xiàn)過程實例詳解

    k8s部署redis集群實現(xiàn)過程實例詳解

    這篇文章主要為大家介紹了k8s部署redis集群實現(xiàn)過程實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-02-02
  • windows平臺安裝部署Redis

    windows平臺安裝部署Redis

    Redis是一個開源、跨平臺的數(shù)據(jù)庫,因此Redis數(shù)據(jù)庫可以運行在Windows、Linux、Mac OS和BSD等多個平臺上,本文主要介紹了windows平臺安裝部署Redis,具有一定的參考價值,感興趣的可以了解一下
    2023-10-10
  • Redis過期鍵與內(nèi)存淘汰策略深入分析講解

    Redis過期鍵與內(nèi)存淘汰策略深入分析講解

    因為redis數(shù)據(jù)是基于內(nèi)存的,然而內(nèi)存是非常寶貴的資源,然后我們就會對一些不常用或者只用一次的數(shù)據(jù)進行存活時間設(shè)置,這樣才能提高內(nèi)存的使用效率,下面這篇文章主要給大家介紹了關(guān)于Redis中過期鍵與內(nèi)存淘汰策略,需要的朋友可以參考下
    2022-11-11
  • Redis分布式鎖一定要避開的兩個坑

    Redis分布式鎖一定要避開的兩個坑

    這篇文章主要為大家詳細介紹了Redis中分布式鎖一定要避開的兩個坑以及對應的解決方法,文中的示例代碼講解詳細,希望對大家有所幫助
    2023-04-04
  • 使用Redis存儲SpringBoot項目中Session的詳細步驟

    使用Redis存儲SpringBoot項目中Session的詳細步驟

    在開發(fā)Spring Boot項目時,我們通常會遇到如何高效管理Session的問題,默認情況下,Spring Boot會將Session存儲在內(nèi)存中,今天,我們將學習如何將Session存儲從內(nèi)存切換到Redis,并驗證配置是否成功,需要的朋友可以參考下
    2024-06-06
  • Redis中?HyperLogLog數(shù)據(jù)類型使用小結(jié)

    Redis中?HyperLogLog數(shù)據(jù)類型使用小結(jié)

    Redis使用HyperLogLog的主要作用是在大數(shù)據(jù)流(view,IP,城市)的情況下進行去重計數(shù),這篇文章主要介紹了Redis中?HyperLogLog數(shù)據(jù)類型使用總結(jié),需要的朋友可以參考下
    2023-03-03
  • Redis中List類型的常用命令

    Redis中List類型的常用命令

    本文主要介紹了Redis中List類型的常用命令,包含12種常用命令,具有一定的參考價值,感興趣的可以了解一下
    2024-06-06
  • Redis動態(tài)熱點數(shù)據(jù)緩存策略設(shè)計

    Redis動態(tài)熱點數(shù)據(jù)緩存策略設(shè)計

    本文主要介紹了Redis動態(tài)熱點數(shù)據(jù)緩存策略設(shè)計,包括熱點數(shù)據(jù)識別、動態(tài)緩存、多級緩存、預加載機制、更新策略以及監(jiān)控告警等,具有一定的參考價值,感興趣的可以了解一下
    2025-01-01
  • 分段存儲Redis鍵值對的方法詳解

    分段存儲Redis鍵值對的方法詳解

    Redis是一種開源的、基于內(nèi)存的數(shù)據(jù)結(jié)構(gòu)存儲系統(tǒng),它可以用作數(shù)據(jù)庫、緩存和消息中間件,Redis最常用的功能之一就是其鍵值對數(shù)據(jù)模型,本文介紹針對一個value過長的鍵值對,如何分段存儲,需要的朋友可以參考下
    2025-01-01

最新評論

屏山县| 武隆县| 武城县| 榆林市| 江华| 钟山县| 易门县| 淳安县| 嘉鱼县| 静宁县| 河北区| 林西县| 奉新县| 麦盖提县| 清镇市| 固镇县| 沙河市| 陈巴尔虎旗| 延津县| 托里县| 梓潼县| 塔河县| 蛟河市| 织金县| 太原市| 民县| 安化县| 榆林市| 科技| 且末县| 玉环县| 沂水县| 盐边县| 西乡县| 奉贤区| 兴文县| 金寨县| 东光县| 深泽县| 绿春县| 福贡县|