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

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

wptr33 2025-03-24 00:20 14 浏览

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常用命令

Redis常用命令

6、 Redis常见应用场景

应用场景

7、 Redis常见的几种特征

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

8、工程结构


工程结构


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

  • Redis 依赖的Jar配置


    org.springframework.boot
    spring-boot-starter-data-redis



    redis.clients
    jedis

  • LuaConfiguration
  • 设置加载限流lua脚本
@Configuration
class LuaConfiguration {
    @Bean
    fun redisScript(): DefaultRedisScript {
        val redisScript = DefaultRedisScript()
        //设置限流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
    @Autowired var redisScript: DefaultRedisScript? = 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(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 {
 
         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(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中的生成器推导式?(生成器推导式的结果是一个)

编程派微信号:codingpy本文作者为NedBatchelder,是一名资深Python工程师,目前就职于在线教育网站Edx。文中蓝色下划线部分可“阅读原文”后点击。Python中有一种紧凑的语法...

Python技巧1:使用Python生成验证码

使用Python生成验证码

别再用手敲了,这个工具可以自动生成python爬虫代码

我们在写爬虫代码时,常常需要各种分析调试,而且每次直接用代码调试都很麻烦所以今天给大家分享一个工具,不仅能方便模拟发送各种http请求,还能轻松调试,最重要的是,可以将调试最终结果自动转换成爬虫代码,...

在 Python 中构建生成式 AI 处理器

为什么不为ApacheNiFi2.0.0创建一个Python处理器?在本教程中,了解这样做的挑战是容易还是困难。当我开始做这件事时,那是一个下雪天。我看到了IBMWatsonXPyt...

一文掌握Python生成器和迭代器之间的区别

迭代器(Iterators)迭代器是遵循迭代器协议的对象,这意味着它们实现了__iter__()和__next__()方法。__iter__()返回迭代器对象本身,__next__()返回容器中的下一...

为你的python程序上锁:软件序列号生成器

序列号很多同学可能开发了非常多的程序了,并且进行了...

5分钟掌握Python(八)之生成器(生成器 python)

1)说明:在Python中,这种一边循环一边计算的机制,称为生成器:generator。在Python中,使用了yield的函数被称为生成器(generator)。跟普通函数不同的是,生成...

python中迭代器和生成器傻傻分不清,别急,这就告诉你区别

杂谈...

使用python生成添加管理员账户的exe

0x01前言在渗透测试中,针对Windows服务器获取webshell后一般会考虑新建管理员账号(当然某些情况下可以直接读密码)登录rdp方便渗透。目前来说,常见的使用netuser(包括激活gu...

人人都能看懂的「迭代器、生成器」入门指南

来源:早起Python作者:刘早起...

用检索增强生成让大模型更强大,这里有个手把手的Python实现

选自towardsdatascience...

Markdown + 文档管理 + 静态网页生成,集大成的 Markdown 应用:MWeb

上周给大家推荐了Typora,作为一款纯粹的Markdown应用来说,它的各种功能和细节可以说已经相当极致,然而,Ulysses用户表示:我们想要的不仅仅是Markdown。是的,Markdo...

python yield -- 生成器(python 生成器send)

概念:yield和return的区别:一个是返回值,一个是迭代器,多次返回python中,yield关键字用于从一个函数中返回一个值,并且能够在之后从同一个位置继续执行。这使得yield成为...

Python生成器(Python生成器对象)

一、Python生成器介绍1.什么是生成器在Python中,使用了...