使用端口解析连接字符串 [英] Parsing a connection string with a port
本文介绍了使用端口解析连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在服务器上有以下连接字符串:
I have the following connections string at a server:
val connStr = "redis://redistogo:fd578d89004321fe@tarpon.redistogo.com:10333/"
我必须使用的 redis 客户端,没有适合此连接字符串的构造函数,它只有一个分别带有主机和端口的构造函数:
The redis client I have to use, doesn't have a constructor appropriate for this connection string, it has only a constructor with a host and a port separately:
class SomeRedisClient(val host: String, val port: Int) { ...
.以下代码也不起作用:
. The following code doesn't work either:
val url = new java.net.URL(connStr)
错误 - java.net.MalformedURLException:未知协议:redis
如何解析这个连接字符串以将其传递给 redis 的构造函数?
How do I parse this connection string to pass it to redis's constructor?
附言我不允许选择其他 redis 客户端.
P.S. I am not allowed to pick other redis client.
推荐答案
使用 URI
String connStr = "redis://redistogo:fd578d89004321fe@tarpon.redistogo.com:10333/";
URI uri = new URI(connStr);
System.out.println(uri.getScheme());
System.out.println(uri.getHost());
System.out.println(uri.getPort());
String connStrWithoutPort = connStr.replace(":" + uri.getPort(), "");
System.out.println(connStrWithoutPort);
// or a more safe version (because the user info part might contain a
// password that matches the port, e.g.
// redis://redistogo:10333@tarpon.redistogo.com:10333/
StringBuilder withoutPort = new StringBuilder();
withoutPort.append(uri.getScheme());
withoutPort.append("://");
String userInfo = uri.getUserInfo();
if (userInfo != null) {
withoutPort.append(userInfo);
withoutPort.append("@");
}
withoutPort.append(uri.getHost());
String withoutPortString = withoutPort.toString();
这篇关于使用端口解析连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文