RabbbitMQ RabbitListener使用IP动态队列 Attribute value must be constant

导读:本篇文章讲解 RabbbitMQ RabbitListener使用IP动态队列 Attribute value must be constant,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

RabbitMQ消息队列使用 @RabbitListener 接收消息,队列名称使用常量命名,但是如果使用动态队列名称,比如根据系统 ip 命名队列名称。

获取服务器 IP

/**
     * 获取服务器ip,解决linux获取ip为127.0.0.1bug
     * @return
     */
    public static String getServerIp() throws SocketException {
        String ip = "";
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface anInterface = en.nextElement();
            String name = anInterface.getName();
            if (!name.contains("docker") && !name.contains("lo")) {
                for (Enumeration<InetAddress> enumIpAddr = anInterface.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    //获得IP
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        String ipaddress = inetAddress.getHostAddress().toString();
                        if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                            if(!"127.0.0.1".equals(ip)){
                                return ipaddress;
                            }
                        }
                    }
                }
            }
        }
        return ip;
    }

创建队列

private String IP_ADDRESS = getServerIp();

@RabbitListener(queues = IP_ADDRESS)
    public void listener(String message) {
        System.out.println(message);
    }

编译报错 Attribute value must be constant

解决方案

  • 创建队列
private String IP_ADDRESS = getServerIp();
 @Bean
    public Queue queue()  {
        return new Queue(IP_ADDRESS);
    }

  • 使用 #{} 引用 bean 名称
@RabbitListener(queues= "#{queue.name}")
    public void listener(String message) {
        System.out.println(message);
    }

#{queue.name} 其中 queuebean 名称,name 是固定。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/22106.html

(0)

相关推荐

半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!