当前位置: 首页 > 后端技术 > Java

RabbitMQ使用IP动态队列属性值必须是常量

时间:2023-04-01 21:26:53 Java

使用@RabbitListener接收RabbitMQ消息队列中的消息,队列名是用常量命名的,但是如果使用动态队列名,比如给队列命名根据系统ip命名。获取服务器IP/***获取服务器ip,解决linux获取ip为127.0.0.1bug*@return*/publicstaticStringgetServerIp()throwsSocketException{Stringip="";for(Enumerationen=NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){NetworkInterfaceanInterface=en.nextElement();Stringname=anInterface.getName();if(!name.contains("docker")&&!name.contains("lo")){for(EnumerationenumIpAddr=anInterface.getInetAddresses();enumIpAddr.hasMoreElements();){//获得IPInetAddressinetAddress=enumIpAddr.nextElement();如果(!inetAddress.isLoopbackAddress()){Stringipaddress=inetAddress.getHostAddress().toString();如果(!ipaddress.contains("::")&&!ipaddress.contains("0:0:")&&!ipaddress.contains("fe80")){if(!"127.0.0.1".equals(ip)){returnipaddress;}}}}}}returnip;}创建队列privateStringIP_ADDRESS=getServerIp();@RabbitListener(queues=IP_ADDRESS)publicvoidlistener(Stringmessage){System.out.println(message);}编译报错Attributevaluemustbeconstant解决方法createqueueprivateStringIP_ADDRESS=getServerIp();@BeanpublicQueuequeue(){returnnewQueue(IP_ADDRESS);}使用#{}引用bean名@RabbitListener(queues="#{queue.name}")publicvoidlistener(Stringmessage){System.out.println(message);}#{queue.name}其中queue是bean名称,名称是固定的