在基于netty的应用中部分场景需要自动识别远端服务,通常是在业务通信前的握手阶段进行识别, 识别指定的服务端并执行相应的逻辑
直接上依赖:
确保使用最新版本nettyx,此处为了演示使用了如下版本
<dependency>
<groupId>io.github.fbbzl</groupId>
<artifactId>nettyx</artifactId>
<version>2.3.3-RELEASE</version>
</dependency>
RemoteDetector
Netty对此部分进行了简单的封装, 提供了ServerDetector来对远端server进行探测, 它的本质是一个单通道的tcpclient实例, 在完成探测之后, 用户可以根据自己需求选择是否close此实例
直接上代码
@Slf4j
public class TestServerDetector extends RemoteDetector<String> {
protected TestServerDetector(InetSocketAddress address) {
super(address);
}
@Override
public boolean checkResponse(String response) {
return StrUtil.equals(response, "ack");
}
@Override
public void initDetectChannel(NioSocketChannel ch) {
ch.pipeline().addLast();
}
@Override
public String getDetectMessage() {
return "this is detect string type msg";
}
public static void main(String[] args) throws Exception {
TestServerDetector testDetector = new TestServerDetector(new InetSocketAddress(9888));
Console.log(testDetector.doDetect());
}
// 简简单单写个main测试下
public static void main(String[] args) throws Exception {
TestServerDetector testDetector = new TestServerDetector(new InetSocketAddress(9888));
// 设置重连的次数
testDetector.setDetectRetryTimes(2);
// 设置最大等待远端响应的毫秒数
testDetector.setWaitResponseMillis(5000);
Console.log(testDetector.doDetect());
}
}
至此我们完成一个简单的探测器