I'm working with Spring AMQP to create queues in RabbitMQ. I'd like to have a queue whose name includes the name of the machine that the app is running on. So the queue name might be "fooQueue.host1" or "fooQueue.host2" depending on where you run the app.

I've figured out a way to do this (detailed below) but it seems a little complicated. Is there an easier/better/Spring-ier way to accomplish this?

My Solution

First make a bean to fetch the machine name:

public class MachineNamePropertyBean {
    public String GetMachineName() throws UnknownHostException {
        InetAddress localMachine = InetAddress.getLocalHost();
        return localMachine.getHostName();
    }
}

Then register the bean in your Spring config:

<bean id="machineNameBean" class="com.example.myapp.MachineNamePropertyBean" />

then use it in your Spring AMQP config like this:

<rabbit:queue id="fooQueue"
              name="fooQueue.#{ machineNameBean.GetMachineName() }"
              durable="false"
              auto-delete="false"
              exclusive="false" />
有帮助吗?

解决方案

There is no other solution unless using SpEL:

<bean id="machineName" class="java.lang.String">
   <constructor-arg value="#{T(java.net.InetAddress).localHost.hostName}"/>
</bean>

<rabbit:queue id="fooQueue"
              name="fooQueue.#{ machineName }"
              durable="false"
              auto-delete="false"
              exclusive="false" />

The same as you are doing, but without new class and via SpEL features.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top