Parsing a connection string with a port

2019-09-03 08:08发布

问题:

I have the following connections string at a server:

val connStr = "redis://redistogo:fd578d89004321fe@tarpon.redistogo.com:10333/"

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)

error - java.net.MalformedURLException: unknown protocol: redis

How do I parse this connection string to pass it to redis's constructor?

P.S. I am not allowed to pick other redis client.

回答1:

Use 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();