Redis+AOP+自定義注解實(shí)現(xiàn)限流
Redis安裝
一提到Redis,相信大家都不會(huì)感到陌生吧。今天就讓我們?cè)诎⒗镌粕习惭b一下Redis,為以后使用它做個(gè)準(zhǔn)備。
下載
1,下載頁面
2,下載
解壓
tar -xzvf redis-5.0.7.tar.gz
準(zhǔn)備編譯
1, 請(qǐng)?jiān)诓僮髑按_認(rèn)gcc是否已安裝,gcc -v
如未安裝,可以執(zhí)行這個(gè)命令安裝:yum install gcc
2,請(qǐng)?jiān)诓僮髑按_認(rèn)tcl是否已安裝如未安裝,可以執(zhí)行這個(gè)命令安裝: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
如果看到以下字樣:表示無錯(cuò)誤:\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è)置以下兩個(gè)地方:
# daemonize no daemonize yes # maxmemory <bytes> maxmemory 128MB
說明:分別是以daemon方式獨(dú)立運(yùn)行 / 內(nèi)存的最大使用限制
運(yùn)行
[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的當(dāng)前版本:
[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方式啟動(dòng)和管理
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)服務(wù)
[root@localhost liuhongdi]# systemctl daemon-reload
4,用來管理redis
啟動(dòng)
systemctl start redis
查看狀態(tài)
systemctl status redis
使開機(jī)啟動(dòng)
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ù)器的端口號(hào),步驟如下:
打開實(shí)例列表,點(diǎn)擊“ 更多”按鈕,選擇“ 網(wǎng)絡(luò)和安全組 ”中的“安全組配置”,選擇 “安全組列表”tab頁面,點(diǎn)擊 “配置規(guī)則”按鈕,點(diǎn)擊 “快速添加”按鈕,勾選“Redis(6379)”,點(diǎn)擊 “確定”之后就可以正常連接了。
3、給redis設(shè)置連接密碼:
查找到# requirepass foobared
注釋去掉并寫入要設(shè)置的密碼,例如:requirepass 123456
redis啟動(dòng)之后測試是否可以連接命令
./redis-cli -h 127.0.0.1 -p 6379 127.0.0.1:6379> auth 123456//此處是你的密碼
注意:如果是阿里云的話一定要設(shè)置密碼,否則很可能被礦機(jī)程序注入定時(shí)任務(wù),用你的服務(wù)器挖礦,阿里云一直會(huì)有信息提示你。
Redis限流
服務(wù)器上的Redis已經(jīng)安裝完成了(安裝步驟見上文),今天就讓我們使用Redis來做個(gè)小功能:自定義攔截器限制訪問次數(shù),也就是限流。
首先我們要在項(xiàng)目中引入Redis
1、引入依賴
<dependency> ? <groupId>org.springframework.boot</groupId> ? <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- redis依賴commons-pool 這個(gè)依賴一定要添加 --> <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: ? ? # 連接池中的最小空閑連接 默認(rèn)0 ? ? ? min-idle: 0 ? ? ? # 連接池中的最大空閑連接 默認(rèn)8 ? ? ? max-idle: 8 ? ? ? # 連接池最大連接數(shù) 默認(rèn)8 ,負(fù)數(shù)表示沒有限制 ? ? ? max-active: 8 ? ? ? # 連接池最大阻塞等待時(shí)間(使用負(fù)值表示沒有限制) 默認(rèn)-1 ? ? ? max-wait: -1ms ? #選擇哪個(gè)庫存儲(chǔ),默認(rèn)是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?{ ? ? ? ?//判斷請(qǐng)求是否屬于方法的請(qǐng)求 ? ? ? ?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進(jìn)行判斷,此處只是例子,不寫具體的業(yè)務(wù) ? ? ? ? ? ? ? ?//..... ? ? ? ? ? ? ? ?key+=""+"1"; ?//這里假設(shè)用戶是1,項(xiàng)目中是動(dòng)態(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","請(qǐng)求超時(shí),請(qǐng)稍后再試"); ? ? ? ? ? ? ? ?render(response,errMap); //這里的CodeMsg是一個(gè)返回參數(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 { ? ?//每三十秒最多可以請(qǐng)求三次,不需要登錄 ? ?@AccessLimit(seconds=30,?maxCount=3,?needLogin=false) ? ?@PostMapping("/fangshua") ? ?public String?fangshua(){ ? ? ? ?return "成功"; ? } }
以上就是Redis+AOP+自定義注解實(shí)現(xiàn)限流的詳細(xì)內(nèi)容,更多關(guān)于Redis限流的資料請(qǐng)關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。