springboot开发网站-使用redis数据库定时特征限制指定ip的访问次数

springboot开发网站-使用redis数据库定时特征限制指定ip的访问次数。近期网站经常有人恶意访问,提交了很多垃圾信息。为了屏蔽这类灌水帖,打算屏蔽ip地址,限制24小时内只能访问1次某个接口。下面是测试的案例代码内容。


1:首先,我们需要增加redis数据库的管理插件maven标记。

<!-- 添加Redis依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2:其次,我们需要增加一个redis的代理管理实体类。

package com.example.guan.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

@Configuration
public class RedisConfig {
    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory(); // 默认连接本地
    }
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        final RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}


声明,如果你是想让这个代理类,链接某个指定的redis库,可以进一步在初始化实体类的过程中,新增参数,包括设置你自己的访问密码。我因为是默认了第一个,所以我就不需要写了。


你还可以设置自己的访问密码信息。


3,有了以上铺垫,我们开启本地redis数据库,然后写一个测试的控制器。试试看。

 

如图,我的本地redis已经开启初始化完成了。服务中。

4:测试控制器代码内容。

package com.example.guan.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.concurrent.TimeUnit;

@RestController
public class MyController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/hello")
    public String handleRequest(HttpServletRequest request) {
        // 1.获取访客IP
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty()) {
            ip = request.getRemoteAddr();
            System.out.println("current user ip:" + ip);
        }

        // 2.使用IP作为key,今天的日期作为prefix
        String key = "rate:limit:" + ip + ":";
        String date = LocalDate.now().toString();
        key += date;
        System.out.println("keyinfo:" + key);

        // 3.检查用户今天的请求次数
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        //查询redis内是否已经存在当前ip日期组合的信息
        Integer count = (Integer) opsForValue.get(key);

        // 4.如果是第一次请求或者超过24小时,重置计数
        if (count == null) {
            count = 0;
            System.out.println("你 first ,ok access this url访问该地址");
            // 更新请求计数
            count++;
            opsForValue.set(key, count, 24, TimeUnit.HOURS); // 设置键的过期时间为24小时
            // 继续处理请求...

        } else if (count != null && count >= 1) {
            return "访问次数超过上限,请明天tomorrow再来访问,谢谢";
        }
        return "请求hello接口地址,反馈数据成功";
    }
}

如图,下图就是测试结果截图。我因为已经访问了一次了,所以第二次请求的时候,就会提示,超过上限,请明天再来访问。

 

我没有做汉字的编码,所以汉字是乱码的。这个不影响我们的redis(信息的反馈结果)。说明,我们读取到了redis数据库内部,已经有这样一个key信息了。

Spring Boot整合MyBatis-Plus和Redis可以通过以下步骤实现: 1. 添加依赖:在pom.xml文件中添加Spring Boot、MyBatis-Plus和Redis的依赖。 ```xml <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> <!-- Redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置数据源:在application.properties或application.yml中配置数据库连接信息。 ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 ``` 3. 配置MyBatis-Plus:创建一个配置类,使用@MapperScan注解指定Mapper接口的扫描路径。 ```java @Configuration @MapperScan("com.example.mapper") public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } } ``` 4. 创建实体类和Mapper接口:创建实体类和对应的Mapper接口,使用注解进行映射。 ```java @Data @TableName("user") public class User { @TableId(type = IdType.AUTO) private Long id; private String name; } ``` ```java @Mapper public interface UserMapper extends BaseMapper<User> { } ``` 5. 添加Redis配置:在application.properties或application.yml中配置Redis连接信息。 ```properties spring.redis.host=localhost spring.redis.port=6379 ``` 6. 编写业务逻辑:创建Service类,注入Mapper和RedisTemplate,并编写业务逻辑。 ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Autowired private RedisTemplate<String, Object> redisTemplate; @Override public User getUserById(Long id) { // 先从缓存中获取数据 String key = "user:" + id; User user = (User) redisTemplate.opsForValue().get(key); // 如果缓存中不存在,则从数据库中获取数据 if (user == null) { user = userMapper.selectById(id); // 将数据存入缓存 redisTemplate.opsForValue().set(key, user); } return user; } } ``` 这样,你就成功地将Spring Boot、MyBatis-Plus和Redis进行了整合。通过MyBatis-Plus进行数据库操作,并通过Redis进行缓存,提高系统性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yrldjsbk

如作品有些帮助,请支持一下我

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值