百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

Kotlin+SpringBoot+Redis+Lua实现限流访问控制详解

liuian 2024-12-25 14:00 43 浏览

1、Redis是简介

  • redis官方网
  • Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。从2010年3月15日起,Redis的开发工作由VMware主持。从2013年5月开始,Redis的开发由Pivotal赞助
  • 工程基于基础架构 Kotlin+SpringBoot+MyBatisPlus搭建最简洁的前后端分离框架美搭建最简洁最酷的前后端分离框架进行完善

2、Redis开发者

  • redis 的作者,叫Salvatore Sanfilippo,来自意大利的西西里岛,现在居住在卡塔尼亚。目前供职于Pivotal公司。他使用的网名是antirez。

3、Redis安装

  • Redis安装与其他知识点请参考几年前我编写文档 Redis Detailed operating instruction.pdf,这里不做太多的描述,主要讲解在kotlin+SpringBoot然后搭建Redis与遇到的问题

Redis详细使用说明书.pdf

https://github.com/jilongliang/kotlin/blob/dev-redis/src/main/resource/Redis%20Detailed%20operating%20instruction.pdf

4、Redis应该学习哪些?

  • 列举一些常见的内容


5、Redis有哪些命令

Redis官方命令清单 https://redis.io/commands

  • Redis常用命令

6、 Redis常见应用场景

7、 Redis常见的几种特征

  • Redis的哨兵机制
  • Redis的原子性
  • Redis持久化有RDB与AOF方式

8、工程结构



9、Kotlin与Redis+Lua的代码实现

  • Redis 依赖的Jar配置
<!-- Spring Boot Redis 依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>
  • LuaConfiguration
  • 设置加载限流lua脚本
@Configuration
class LuaConfiguration {
    @Bean
    fun redisScript(): DefaultRedisScript<Number> {
        val redisScript = DefaultRedisScript<Number>()
        //设置限流lua脚本
        redisScript.setScriptSource(ResourceScriptSource(ClassPathResource("limitrate.lua")))
        //第1种写法反射转换Number类型
        //redisScript.setResultType(Number::class.java)
        //第2种写法反射转换Number类型
        redisScript.resultType = Number::class.java
        return redisScript
    }
}
  • Lua限流脚本
local key = "request:limit:rate:" .. KEYS[1]    --限流KEY
local limitCount = tonumber(ARGV[1])            --限流大小
local limitTime = tonumber(ARGV[2])             --限流时间
local current = tonumber(redis.call('get', key) or "0")
if current + 1 > limitCount then --如果超出限流大小
    return 0
else  --请求数+1,并设置1秒过期
    redis.call("INCRBY", key,"1")
    redis.call("expire", key,limitTime)
    return current + 1
end

  • RateLimiter自定义注解
  • 1、Java自定义注解Target使用@Target(ElementType.TYPE, ElementType.METHOD)
  • 2、Java自定义注解Retention使用@Retention(RetentionPolicy.RUNTIME)
  • 3、Kotlin自定义注解Target使用@Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION)
  • 4、Kotlin自定义注解Target使用@Retention(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION)

@Target(AnnotationTarget.TYPE, AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class RateLimiter(
        /**
         * 限流唯一标识
         * @return
         */
        val key: String = "",
        /**
         * 限流时间
         * @return
         */
        val time: Int,
        /**
         * 限流次数
         * @return
         */
        val count: Int
 )

限流AOP的Aspect切面实现

import com.flong.kotlin.core.annotation.RateLimiter
import com.flong.kotlin.core.exception.BaseException
import com.flong.kotlin.core.exception.CommMsgCode
import com.flong.kotlin.core.vo.ErrorResp
import com.flong.kotlin.utils.WebUtils
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.reflect.MethodSignature
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.data.redis.core.script.DefaultRedisScript
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import java.util.*


@Suppress("SpringKotlinAutowiring")
@Aspect
@Configuration
class RateLimiterAspect {
    @Autowired lateinit var redisTemplate: RedisTemplate<String, Any>
    @Autowired var redisScript: DefaultRedisScript<Number>? = null

    /**
     * 半生对象
     */
    companion object {
        private val log: Logger = LoggerFactory.getLogger(RateLimiterAspect::class.java)
    }

    @Around("execution(* com.flong.kotlin.modules.controller ..*(..) )")
    @Throws(Throwable::class)
    fun interceptor(joinPoint: ProceedingJoinPoint): Any {

        val signature = joinPoint.signature as MethodSignature
        val method = signature.method
        val targetClass = method.declaringClass
        val rateLimit = method.getAnnotation(RateLimiter::class.java)

        if (rateLimit != null) {
            val request = (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes).request
            val ipAddress = WebUtils.getIpAddr(request = request)

            val stringBuffer = StringBuffer()
            stringBuffer.append(ipAddress).append("-")
                    .append(targetClass.name).append("- ")
                    .append(method.name).append("-")
                    .append(rateLimit!!.key)

            val keys = Collections.singletonList(stringBuffer.toString())

            print(keys + rateLimit!!.count + rateLimit!!.time)
            val number = redisTemplate!!.execute<Number>(redisScript, keys, rateLimit!!.count, rateLimit!!.time)

            if (number != null && number!!.toInt() != 0 && number!!.toInt() <= rateLimit!!.count) {
                log.info("限流时间段内访问第:{} 次", number!!.toString())
                return joinPoint.proceed()
            }

        } else {
            var proceed: Any? = joinPoint.proceed() ?: return ErrorResp(CommMsgCode.SUCCESS.code!!, CommMsgCode.SUCCESS.message!!)
            return joinPoint.proceed()
        }
        throw BaseException(CommMsgCode.RATE_LIMIT.code!!, CommMsgCode.RATE_LIMIT.message!!)
    }
}

WebUtils代码


import javax.servlet.http.HttpServletRequest

/**
 * User: liangjl
 * Date: 2020/7/28
 * Time: 10:01
 */
object WebUtils {
    fun getIpAddr(request: HttpServletRequest): String? {
        var ipAddress: String? = null
        try {
            ipAddress = request.getHeader("x-forwarded-for")
            if (ipAddress == null || ipAddress!!.length == 0 || "unknown".equals(ipAddress!!, ignoreCase = true)) {
                ipAddress = request.getHeader("Proxy-Client-IP")
            }
            if (ipAddress == null || ipAddress!!.length == 0 || "unknown".equals(ipAddress!!, ignoreCase = true)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP")
            }
            if (ipAddress == null || ipAddress!!.length == 0 || "unknown".equals(ipAddress!!, ignoreCase = true)) {
                ipAddress = request.getRemoteAddr()
            }
            // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress!!.length > 15) {
                // "***.***.***.***".length()= 15
                if (ipAddress!!.indexOf(",") > 0) {
                    ipAddress = ipAddress!!.substring(0, ipAddress.indexOf(","))
                }
            }
        } catch (e: Exception) {
            ipAddress = ""
        }
        return ipAddress
    }
}
  • Controller代码
 @RestController
 @RequestMapping("rest")
 class RateLimiterController {
     companion object {
         private val log: Logger = LoggerFactory.getLogger(RateLimiterController::class.java)
     }
 
     @Autowired
     private val redisTemplate: RedisTemplate<*, *>? = null
 
     @GetMapping(value = "/limit")
     @RateLimiter(key = "limit", time = 10, count = 1)
     fun limit(): ResponseEntity<Any> {
 
         val date = DateFormatUtils.format(Date(), "yyyy-MM-dd HH:mm:ss.SSS")
         val limitCounter = RedisAtomicInteger("limit:rate:counter", redisTemplate!!.connectionFactory!!)
         val str = date + " 累计访问次数:" + limitCounter.andIncrement
         log.info(str)
 
         return ResponseEntity.ok<Any>(str)
     }
 }

注意:RedisTemplateK, V>这个类由于有K与V,下面的做法是必须要指定Key-Value 2 type arguments expected for class RedisTemplate

  • 运行结果
  • 访问地址:http://localhost:8080/rest/limit




10、参考文章

参考分布式限流之Redis+Lua实现参考springboot + aop + Lua分布式限流的最佳实践

11、工程架构源代码

Kotlin+SpringBoot+Redis+Lua实现限流访问控制详解工程源代码

https://github.com/jilongliang/kotlin/tree/dev-lua

12 、总结与建议

  • 1 、以上问题根据搭建 kotlin与Redis实际情况进行总结整理,除了技术问题查很多网上资料,通过自身进行学习之后梳理与分享。
  • 2、 在学习过程中也遇到很多困难和疑点,如有问题或误点,望各位老司机多多指出或者提出建议。本人会采纳各种好建议和正确方式不断完善现况,人在成长过程中的需要优质的养料。
  • 3、 希望此文章能帮助各位老铁们更好去了解如何在 kotlin上搭建RabbitMQ,也希望您看了此文档或者通过找资料进行手动安装效果会更好。

备注:此文章属于本人原创,欢迎转载和收藏.

相关推荐

赶紧收藏!编程python基础知识,本文给你全部整理好了

想一起学习编程Python的同学,趁我粉丝少,可以留言、私信领编程资料~Python基础入门既然学习Python,那么至少得了解下这门编程语言,知道Python代码执行过程吧。Python的历...

创建绩效改进计划 (PIP) 的6个步骤

每个经理都必须与未能达到期望的员工抗衡,也许他们的表现下降了,他们被分配了新的任务并且无法处理它们,或者他们处理了自己的任务,但他们的行为对他人造成了破坏。许多公司转向警告系统,然后在这些情况下终止。...

PI3K/AKT信号通路全解析:核心分子、上游激活与下游效应分子

PI3K/AKT/mTOR(PAM)信号通路是真核细胞中高度保守的信号转导网络,作用于促进细胞存活、生长和细胞周期进程。PAM轴上生长因子向转录因子的信号传导受到与其他多条信号通路的多重交叉相互作用的...

互联网公司要求签PIP,裁员连N+1都没了?

2021年刚画上句号,令无数互联网公司从业者闻风丧胆的绩效公布时间就到了,脉脉上已然炸了锅。阿里3.25、腾讯二星、百度四挡、美团绩效C,虽然名称五花八门,实际上都代表了差绩效。拿到差绩效,非但不能晋...

Python自动化办公应用学习笔记3—— pip工具安装

3.1pip工具安装最常用且最高效的Python第三方库安装方式是采用pip工具安装。pip是Python包管理工具,提供了对Python包的查找、下载、安装、卸载的功能。pip是Python官方提...

单片机都是相通的_单片机是串行还是并行

作为一个七年的从业者,单片机对于我个人而言它是一种可编程的器件,现在长见到的电子产品中几乎都有单片机的身影,它们是以单片机为核心,根据不同的功能需求,搭建不同的电路,从8位的单片机到32位的单片机,甚...

STM32F0单片机快速入门八 聊聊 Coolie DMA

1.苦力DMA世上本没有路,走的人多了,便成了路。世上本没有DMA,需要搬运的数据多了,便有了DMA。大多数同学应该没有在项目中用过这个东西,因为一般情况下也真不需要这个东西。在早期的单片机中...

放弃51单片机,直接学习STM32开发可能会面临的问题

学习51单片机并非仅仅是为了学习51本身,而是通过它学习一种方法,即如何仅仅依靠Datasheet和例程来学习一种新的芯片。51单片机相对较简单,是这个过程中最容易上手的选择,而AVR单片机则更为复杂...

STM32串口通信基本原理_stm32串口原理图

通信接口背景知识设备之间通信的方式一般情况下,设备之间的通信方式可以分成并行通信和串行通信两种。并行与串行通信的区别如下表所示。串行通信的分类1、按照数据传送方向,分为:单工:数据传输只支持数据在一个...

单片机的程序有多大?_单片机的程序有多大内存

之前一直很奇怪一个问题,每次写好单片机程序之后,用烧录软件进行烧录时,能看到烧录文件也就是hex的文件大小:我用的单片机芯片是STM32F103C8T6,程序储存器(flash)只有64K。从...

解析STM32单片机定时器编码器模式及其应用场景

本文将对STM32单片机定时器编码器模式进行详细解析,包括介绍不同的编码器模式、各自的优缺点以及相同点和不同点的应用场景。通过阅读本文,读者将对STM32单片机定时器编码器模式有全面的了解。一、引言...

两STM32单片机串口通讯实验_两个32单片机间串口通信

一、实验思路连接两个STM32单片机的串口引脚,单片机A进行发送,单片机B进行接收。单片机B根据接收到单片机A的指令来点亮或熄灭板载LED灯,通过实验现象来验证是否通讯成功。二、实验器材两套STM32...

基于单片机的智能考勤机设计_基于51单片机的指纹考勤机

一、设计背景随着科技水平的不断发展,在这么一个信息化的时代,智能化信息处理已是提高效率、规范管理和客观审查的最有效途径。近几年来,国内很多公司都在加强对企业人员的管理,考勤作为企业的基础管理,是公司...

STM32单片机详细教学(二):STM32系列单片机的介绍

大家好,今天给大家介绍STM32系列单片机,文章末尾附有本毕业设计的论文和源码的获取方式,可进群免费领取。前言STM32系列芯片是为要求高性能、低成本、低功耗的嵌入式应用设计的ARMCortexM...

STM32单片机的 Hard-Fault 硬件错误问题追踪与分析

有过单片机开发经验的人应该都会遇到过硬件错误(Hard-Fault)的问题,对于这样的问题,有些问题比较容易查找,有些就查找起来很麻烦,甚至可能很久都找不到问题到底是出在哪里。特别是有时候出现一次,后...