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(); 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 { ch.pipeline().addLast(new IpFilterRuleHandler()); } }) );
|
快来实践看结果吧