温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring Boot ActiveMQ设置访问密码的方法

发布时间:2020-07-03 09:20:58 来源:亿速云 阅读:210 作者:清晨 栏目:开发技术

这篇文章将为大家详细讲解有关Spring Boot ActiveMQ设置访问密码的方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

Apache ActiveMQ是Apache出品,是最流行的,能力很强的开源消息总线。默认情况下,程序连接ActiveMQ是不需要密码的,为了安装起见,需要设置密码,提高安全性。

小编使用的ActiveMQ版本是apache-activemq-5.15.13。

一、设置控制台管理密码

ActiveMQ使用的是jetty服务器,找到 ActiveMQ安装目录下的\conf\jetty.xml文件:

<bean id="adminSecurityConstraint" class="org.eclipse.jetty.util.security.Constraint">
  <property name="name" value="BASIC" />
  <property name="roles" value="admin" />
  <!-- set authenticate=false to disable login -->
  <property name="authenticate" value="true" />
</bean>

注意:authenticate的属性默认为"true",登录管理界面时需要输入账户和密码;如果是“false”,需要改为"true"。

修改管理界面登录时的用户名和密码,在conf/jetty-realm.properties文件中添加用户

## ---------------------------------------------------------------------------
## Licensed to the Apache Software Foundation (ASF) under one or more
## contributor license agreements. See the NOTICE file distributed with
## this work for additional information regarding copyright ownership.
## The ASF licenses this file to You under the Apache License, Version 2.0
## (the "License"); you may not use this file except in compliance with
## the License. You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
## ---------------------------------------------------------------------------

# Defines users that can access the web (console, demo, etc.)
# username: password [,rolename ...]
# admin: admin, admin
# user: user, user
wiener: wiener1237, admin

配置信息按顺序解释,分别是:用户名、密码、角色名

二、消息生产者和消费者密码认证

在\conf\activemq.xml中broker 标签最后添加生产者和消费者密码认证信息:

<!-- destroy the spring context on shutdown to stop jetty -->
    <shutdownHooks>
      <bean xmlns="http://www.springframework.org/schema/beans" class="org.apache.activemq.hooks.SpringContextHook" />
    </shutdownHooks>
    <!-- add plugins -->
    <plugins>
      <simpleAuthenticationPlugin>
        <users>
          <authenticationUser username="${activemq.username}" password="${activemq.password}" groups="users,admins"/>
        </users>
      </simpleAuthenticationPlugin>
    </plugins>
  </broker>

activemq.username和activemq.password的值在文件credentials.properties中配置,见如下步骤。

设置用户名密码,文件在\conf\credentials.properties

## ---------------------------------------------------------------------------
## Licensed to the Apache Software Foundation (ASF) under one or more
## contributor license agreements. See the NOTICE file distributed with
## this work for additional information regarding copyright ownership.
## The ASF licenses this file to You under the Apache License, Version 2.0
## (the "License"); you may not use this file except in compliance with
## the License. You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
## ---------------------------------------------------------------------------

# Defines credentials that will be used by components (like web console) to access the broker

# activemq.username=system
# activemq.password=manager
# guest.password=password

activemq.username=wiener
activemq.password=wiener1237
guest.password=password

三、Java端配置用户名密码

验证代码是在《【Spring Boot】ActiveMQ 发布/订阅消息模式介绍》的基础上做重构,除了新增类ActiveMQConfig之外,修改部分均用红色字体标注。配置application.properties连接信息:

## URL of the ActiveMQ broker. Auto-generated by default. For instance `tcp://localhost:61616`
# failover:(tcp://localhost:61616,tcp://localhost:61617)
# tcp://localhost:61616
spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.in-memory=true
spring.activemq.pool.enabled=false
#默认值false,表示point to point(点到点)模式,true时代表发布订阅模式,需要手动开启
spring.jms.pub-sub-domain=true
spring.activemq.user=wiener
spring.activemq.password=wiener1237

在项目中配置 ActiveMQ连接属性,新增ActiveMQConfig类:

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;

/**
* 配置 ActiveMQ
*
* @author east7
* @date 2020/6/23 11:27
*/
@Configuration
public class ActiveMQConfig {

  @Value("${spring.activemq.user}")
  private String usrName;

  @Value("${spring.activemq.password}")
  private String password;

  @Value("${spring.activemq.broker-url}")
  private String brokerUrl;

  @Bean
  public ActiveMQConnectionFactory connectionFactory() {
    System.out.println("password =========== " + password);
    return new ActiveMQConnectionFactory(usrName, password, brokerUrl);
  }

  /**
   * 设置点对点模式,和下面的发布订阅模式二选一即可
   * @param connectionFactory
   * @return
   */
  @Bean
  public JmsListenerContainerFactory<&#63;> jmsListenerContainerQueue(ActiveMQConnectionFactory connectionFactory){
    DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
    bean.setConnectionFactory(connectionFactory);
    return bean;
  }

  @Bean
  public JmsListenerContainerFactory<&#63;> jmsListenerContainerTopic(ActiveMQConnectionFactory connectionFactory){
    //设置为发布订阅模式, 默认情况下使用生产消费者方式
    DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
    bean.setPubSubDomain(true);
    bean.setConnectionFactory(connectionFactory);
    return bean;
  }
}

bean.setPubSubDomain(true)配置会覆盖properties文件中spring.jms.pub-sub-domain的属性值,故可以在properties不设置spring.jms.pub-sub-domain属性。另外,这种配置方式可以在系统中同时使用点对点和发布/订阅两种消息模式。修改订阅者:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;

/**
* 消费者
*/
@Component
public class Subscriber1 {
  private static Logger logger = LoggerFactory.getLogger(Subscriber1.class);
  /**
   * 订阅 topicListener1,仅仅加入containerFactory即可
   *
   * @param text
   * @throws JMSException
   */
  @JmsListener(destination = "topicListener1", containerFactory = "jmsListenerContainerTopic")
  public void subscriber(String text) {
    logger.info("Subscriber1 收到的报文:{}", text);
  }
}

containerFactory 的值 "jmsListenerContainerTopic" 会自动匹配到ActiveMQConfig中的函数JmsListenerContainerFactory<&#63;> jmsListenerContainerTopic(ActiveMQConnectionFactory connectionFactory)。 Subscriber2同样修改即可,代码省略。如果containerFactory 的值设置为jmsListenerContainerQueue,则开启了点到点消息模式。

测试函数还可以使用topicTest()。下面提供一个新的测试途径——在controller中测试。新增方法

@Autowired
private Publisher publisher;

@GetMapping("/sendTopicMsg")
public String sendTopicMsg(String msg) {
  // 指定消息发送的目的地及内容
  Destination destination = new ActiveMQTopic("topicListener2");
  for (int i = 0; i < 8; i++) {
    publisher.publish(destination, msg + i);
  }
  return msg + " 发送完毕";
}

关于Spring Boot ActiveMQ设置访问密码的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI