We can use both a standard Java URI object, as defined in the java.net package, or a String in the expected AMQP format. Let's say that we already have the URI as a string, and we can pass it to our rabbit application, we can use this information directly:
private ConnectionFactory getFactory(String uri) throws IOException { // 1 ConnectionFactory factory = new ConnectionFactory(); try { factory.setUri(uri); // 2 } catch (URISyntaxException|NoSuchAlgorithmException|KeyManagementException e) { throw new IOException("Can't set connection factory URI", e); // 3 } return factory; }1. We expect uri to be something like "amqp://user:password@127.0.0.1:6391/test", where "test" is the name of our virtual host. We are not forced to specify all parts in the AMQP URI, but the host name must be passed if at least one property among username, password, or port is given.
2. The passed URI is carefully checked, and three different exceptions could be thrown to acknowledge a specific error.
3. The error handling here is very loose, any passible exception is converted in an IOException and forwarded to the caller. The reason for this is just keeping the code simple, since I don't care much of having such detailed information on the reason for failure. This shouldn't be an optimal choice for production code.
Producer and consumer should be slightly changed to try-catch also on this method:
public void consumer(String uri) { try { ConnectionFactory factory = getFactory(uri); Connection connection = factory.newConnection(); // ... connection.close(); } catch (IOException|InterruptedException e) { e.printStackTrace(); } }
No comments:
Post a Comment