IP黑名单介绍实战

根据官方文档发现RuleBasedIpFilter,进行IP过滤实现黑白名单处理。
官方文档地址如下:https://netty.io/4.1/api/io/netty/handler/ipfilter/IpFilterRule.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class IpFilterRuleHandler extends RuleBasedIpFilter {
private BlackService blackService = SpringUtil.getBean(BlackService.class);
@Override
protected boolean accept(ChannelHandlerContext ctx, InetSocketAddress remoteAddress) throws Exception {
String hostAddress = remoteAddress.getHostString();//ip信息
IpFilterRuleType filterRuleType = IpFilterRuleType.ACCEPT;//通过
if(StrUtil.isNotBlank(hostAddress)){
boolean isReject = blackService.checkBlackList(hostAddress);//检测实时黑名单
if(isReject){
filterRuleType = IpFilterRuleType.REJECT;//拒绝创建
}
}
return filterRuleType == IpFilterRuleType.ACCEPT;
}
}

当然IP过滤处理掉我们如何使用呢

1
2
3
4
5
6
7
8
9
10
11
 //代码片段
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
public void initChannel(NioSocketChannel ch) throws Exception {
// 注册handler
ch.pipeline().addLast(new IpFilterRuleHandler());//添加IP过滤
}
})
);

快来实践看结果吧