Springboot 限制IP訪問指定的網(wǎng)址實現(xiàn)
IP黑白名單是網(wǎng)絡安全管理中常見的策略工具,用于控制網(wǎng)絡訪問權限,根據(jù)業(yè)務場景的不同,其應用范圍廣泛

方式一:
添加一個簡單的白名單,然后只有白名單上面的 IP 才能訪問網(wǎng)站,否則不能訪問這是只是一個很簡單的實現(xiàn)方法
首先:在 application.yml 配置 IP 白名單
my:
ipList:
- 192.168.3.3
- 192.168.2.12
- 192.168.5.24
- 152.63.54.26
想要引用到配置文件里面的 String 數(shù)組,如果使用普通的 @Value 是不行的,必須使用其他方法
步驟一:創(chuàng)建一個實體類
@Component
@ConfigurationProperties(prefix = "my") // 這里是對應的配置文件里面自定義的 my
public class My {
private String[] ipList;
public My(String[] ipList) {
this.ipList = ipList;
}
public String[] getIpList() {
return ipList;
}
public void setIpList(String[] ipList) {
this.ipList = ipList;
}
}
這樣配置文件的信息就保存在了這個實體類里面
在 Controller 里面比對 IP
@Controller
public class LoginController {
@Autowired
private My myIpList;
@PostMapping("/login")
@ResponseBody
public String login(@RequestBody LoginForm loginForm, HttpServletRequest request) {
String [] ipList = myIpList.getIpList();
String IPAddress = loginForm.getIpAddress();
// 如果前端傳遞過來的 IP 在白名單里面,就返回 OK,如果不在,就返回 error
for (String s : ipList) {
if (s.equals(IPAddress)) {
return "OK";
}
}
return "error";
}
}
方式二:限制 IP 訪問的次數(shù)
這個是利用了 aop 的切面編程,如果同一個 IP 訪問一個地址一分鐘之內(nèi)超過10次,就會把這個 IP 拉入黑名單,在自定義的時間內(nèi)是不能再次訪問這個網(wǎng)站的。
第一步,在 application.yml 中配置 Redis 相關設置
spring:
redis:
# 超時時間
timeout: 10000ms
# 服務器地址
host: 192.168.1.1
# 服務器端口
port: 6379
# 數(shù)據(jù)庫
database: 0
# 密碼
password: xxxxxxx
lettuce:
pool:
# 最大連接數(shù),默認為 8
max-active: 1024
# 最大連接阻塞等待時間,默認 -1
max-wait: 10000ms
# 最大空閑連接
max-idle: 200
# 最小空閑連接
min-idle: 5
第一步,自定義一個注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface RequestLimit {
/**
* 允許訪問的最大次數(shù)
*/
int count() default Integer.MAX_VALUE;
/**
* 時間段,單位為毫秒,默認值一分鐘
*/
long time() default 60000;
}
第二步:序列化 redis 類
@Configuration
@Slf4j
public class RedisConfiguration {
@Bean
@ConditionalOnMissingBean
public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
System.err.println("調(diào)用了 Redis 配置類");
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
// String 類型 key 序列器
redisTemplate.setKeySerializer(new StringRedisSerializer());
// String 類型 value 序列器
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// Hash 類型 value 序列器
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
// Hash 類型 value 序列器
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setConnectionFactory(connectionFactory);
return redisTemplate;
}
}
第三步:創(chuàng)建一個切面類
@Aspect
@Component
@Slf4j
public class RequestLimitContract {
private static final Logger logger = LoggerFactory.getLogger("requestLimitLogger");
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private ObjectMapper objectMapper;
@Before("within(@org.springframework.stereotype.Controller *) && @annotation(limit)")
public void requestLimit(final JoinPoint joinPoint , RequestLimit limit) throws RequestLimitException {
try {
LoginForm loginForm = new LoginForm();
Object[] args = joinPoint.getArgs();
HttpServletRequest request = null;
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof HttpServletRequest) {
request = (HttpServletRequest) args[i];
break;
} else if (args[i] instanceof LoginForm) {
loginForm = (LoginForm) args[i];
}
}
if (request == null) {
throw new RequestLimitException("方法中缺失HttpServletRequest參數(shù)");
}
//獲取請求中的ip與url鏈接參數(shù) 用于拼接key存放redis中
String ip = loginForm.getIpAddress();
String url = request.getRequestURL().toString();
Long interview_time = new Date().getTime();
String key = "req_limit_".concat(url).concat("---").concat(ip);
System.err.println("準備保存在redis中的數(shù)據(jù)為-->");
Map<String, Long> form = new HashMap<>();
form.put("size", 1L);
form.put("saveRedisTime", interview_time);
if (redisTemplate.opsForValue().get(key) == null) {
System.err.println(form);
redisTemplate.opsForValue().set(key, form);
} else {
//用于進行ip訪問的計數(shù)
Map<String, Long> result = (Map<String, Long>) redisTemplate.opsForValue().get(key);
System.err.println("從redis取到的數(shù)據(jù)(內(nèi)部)");
System.out.println(result);
assert result != null;
result.put("size", result.get("size") + 1);
redisTemplate.opsForValue().set(key, result);
if (result.get("size") > 10) {
logger.info("用戶IP[" + ip + "]訪問地址[" + url + "]超過了限定的次數(shù)[" + limit.count() + "]");
throw new RequestLimitException();
}
// 如果訪問次數(shù)小于 10 次,那么一分鐘過后就直接刪除這個節(jié)點
if (result.get("size") <= limit.count()) {
//創(chuàng)建一個定時器
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
redisTemplate.delete(key);
}
};
//這個定時器設定在time規(guī)定的時間之后會執(zhí)行上面的remove方法,也就是說在這個時間后它可以重新訪問
timer.schedule(timerTask, limit.time());
}
}
}catch (RequestLimitException e){
throw e;
}catch (Exception e){
logger.error("發(fā)生異常",e);
}
}
}
第四步,創(chuàng)建一個定時器
記住要在啟動類上面開啟啟動定時器注解
@Component
public class ScheduledTask {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// @Value("${properties.continueTime}")
private final long continueTime = 120; // 這是是黑名單的保存時間,在這個時間內(nèi),同一個IP將不能繼續(xù)訪問
// @Scheduled(cron = "0 0 0 * * ?") // 每天凌晨觸發(fā)一次
@Scheduled(fixedRate = 1000000) // 每 30s 執(zhí)行一次
public void deleteDataScheduled() {
Set<String> keys = redisTemplate.keys("*");
if (keys == null || keys.size() == 0) {
return;
}
System.out.println("redis里面所有的key為:" + keys.toString());
long now_time = new Date().getTime();
for (String key : keys) {
Map<String, Long> result = (Map<String, Long>) redisTemplate.opsForValue().get(key);
assert result != null;
System.err.println(result);
// 計算出時間差
long createTime = result.get("saveRedisTime");
System.err.println("創(chuàng)建時間為:" + createTime);
long l = (now_time - createTime) / 1000L;
System.err.println("時間差為:" + l);
if (l > continueTime) {
System.out.println("禁止時間結(jié)束,解除時間限制?。?!");
redisTemplate.delete(key);
return;
}
int s = Math.toIntExact(result.get("size"));
System.out.println("s===>" + s + " l===>" + l);
if (s <= 10) {
if (l > 60) {
System.out.println("一分鐘結(jié)束,刪除節(jié)點,重新計時");
redisTemplate.delete(key);
}
}
}
}
}
第五步:在需要的類上使用自己自定義的注解
@PostMapping("/login")
@RequestLimit(count=10,time=60000) // 這個注解就是開啟IP限制的注解,這個注解的業(yè)務都是自己寫的
@ResponseBody
public String login(@RequestBody LoginForm loginForm, HttpServletRequest request) {
System.out.println("執(zhí)行登錄代碼");
String name = loginForm.getUsername();
String IPAddress = loginForm.getIpAddress();
String timestamp = String.valueOf(new Date().getTime());
String info = Arrays.toString(ipList);
request.setAttribute("userName", name);
request.setAttribute("ipAddress", IPAddress);
return "OK1";
}
總結(jié):在這里針對 IP 的限制就結(jié)束了,總而言之還是比較簡單的,沒有什么特別難的點
到此這篇關于Springboot 限制IP訪問指定的網(wǎng)址實現(xiàn)的文章就介紹到這了,更多相關Springboot 限制IP訪問指定網(wǎng)址內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java同步關鍵字synchronize底層實現(xiàn)原理解析
synchronized關鍵字對大家來說并不陌生,當我們遇到并發(fā)情況時,優(yōu)先會想到用synchronized關鍵字去解決,synchronized確實能夠幫助我們?nèi)ソ鉀Q并發(fā)的問題,接下來通過本文給大家分享java synchronize底層實現(xiàn)原理,感興趣的朋友一起看看吧2021-08-08
SpringBoot項目多模塊項目中父類與子類pom.xml的關聯(lián)問題小結(jié)
這篇文章主要介紹了SpringBoot項目多模塊項目中父類與子類pom.xml的關聯(lián)問題,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2025-04-04
SpringBoot中優(yōu)化if-else語句的七種方法
if-else語句是控制流程的基本工具,但過度使用會使代碼變得復雜且難以維護,在SpringBoot , SpringCloud項目中,優(yōu)化if-else結(jié)構(gòu)變得尤為重要,本文將深入探討七種策略,旨在減少SpringBoot , SpringCloud項目中 if-else的使用,需要的朋友可以參考下2024-07-07

